home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.006 / xemacs-1 / lib / xemacs-19.13 / lisp / dired / dired.el < prev    next >
Encoding:
Text File  |  1995-08-15  |  143.3 KB  |  3,757 lines

  1. ;;; dired.el --- directory-browsing commands
  2. ;; Keywords: dired extensions
  3.  
  4. ;; Copyright (C) 1985, 1986, 1991, 1992 Free Software Foundation, Inc.
  5.  
  6. ;; This file is part of XEmacs.
  7.  
  8. ;; XEmacs is free software; you can redistribute it and/or modify it
  9. ;; under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation; either version 2, or (at your option)
  11. ;; any later version.
  12.  
  13. ;; XEmacs is distributed in the hope that it will be useful, but
  14. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  16. ;; General Public License for more details.
  17.  
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with XEmacs; see the file COPYING.  If not, write to the Free
  20. ;; Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  21.  
  22. ;; Rewritten in 1990/1991 to add tree features, file marking and
  23. ;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
  24.  
  25. (provide 'dired)
  26.  
  27. (defconst dired-version (substring "!Revision: 6.0 !" 11 -2)
  28.   "The revision number of Tree Dired (as string).  The complete RCS id is:
  29.  
  30.   !Id: dired.el,v 6.0 1992/05/15 14:25:45 sk RelBeta !
  31.  
  32. Don't forget to mention this when reporting bugs to:
  33.  
  34.   Sebastian Kremer <sk@thp.uni-koeln.de>
  35.  
  36. Tree dired is available for anonymous ftp in USA in:
  37.  
  38.   ftp.cs.buffalo.edu:pub/Emacs/diredall.tar.Z
  39.  
  40. and in Europe at my own site in Germany:
  41.  
  42.   ftp.uni-koeln.de:/pub/gnu/emacs/diredall.tar.Z")
  43. ;; Should perhaps later give bug-gnu-emacs@prep.gnu.ai.mit.edu instead.
  44.  
  45. ;; compatibility package when using Emacs 18.55
  46. (defvar dired-emacs-19-p (equal (substring emacs-version 0 2) "19"))
  47. ;;;#### install (is there a better way to test for Emacs 19?)
  48. (or dired-emacs-19-p
  49.     (require 'emacs-19))
  50.  
  51. ;;; Customizable variables
  52.  
  53. ;;; The funny comments are for autoload.el, to automagically update
  54. ;;; loaddefs.
  55.  
  56. (defvar dired-use-gzip-instead-of-compress t
  57.   "*If non-nil, use gzip instead of compress as the standard compress
  58. program")
  59.  
  60. (defvar dired-make-gzip-quiet t
  61.   "*If non-nil, pass -q to shell commands involving gzip this will override
  62. GZIP environment variable.")
  63.  
  64. (defvar dired-znew-switches nil
  65.   "*If non-nil, a string of switches that will be passed to `znew'
  66. example: \"-K\"")
  67.  
  68. (defvar dired-gzip-file-extension ".gz"
  69.   "*A string representing the suffix created by gzip.  This should probably
  70. match the value of --suffix or -S in the GZIP environment variable if it
  71. exists and \".gz\" if it does not.")
  72.  
  73. ;;;###autoload
  74. (defvar dired-listing-switches (purecopy "-al")
  75.   "*Switches passed to ls for dired. MUST contain the `l' option.
  76. Can contain even `F', `b', `i' and `s'.")
  77.  
  78. ; Don't use absolute paths as /bin should be in any PATH and people
  79. ; may prefer /usr/local/gnu/bin or whatever.  However, chown is
  80. ; usually not in PATH.
  81.  
  82. ;;;###autoload
  83. (defvar dired-chown-program
  84.   (purecopy
  85.    (if (memq system-type '(dgux-unix hpux usg-unix-v silicon-graphics-unix))
  86.        "chown" "/etc/chown"))
  87.   "*Name of chown command (usully `chown' or `/etc/chown').")
  88.  
  89. ;;;###autoload
  90. (defvar dired-ls-program (purecopy "ls")
  91.   "*Absolute or relative name of the ls program used by dired.")
  92.  
  93. ;;;###autoload
  94. (defvar dired-ls-F-marks-symlinks t
  95.   "*Informs dired about how ls -lF marks symbolic links.
  96. Set this to t if `dired-ls-program' with -lF marks the symbolic link
  97. itself with a trailing @ (usually the case under Ultrix).
  98.  
  99. Example: if `ln -s foo bar; ls -F bar' gives `bar -> foo', set it to
  100. nil, if it gives `bar@ -> foo', set it to t.
  101.  
  102. Dired checks if there is really a @ appended.  Thus, if you have a
  103. marking ls program on one host and a non-marking on another host, and
  104. don't care about symbolic links which really end in a @, you can
  105. always set this variable to t.")
  106.  
  107. ;;;###autoload
  108. (defvar dired-trivial-filenames (purecopy "^\\.\\.?$\\|^#")
  109.   "*Regexp of files to skip when moving point to the first file of a new directory listing.
  110. Nil means move to the subdir line, t means move to first file.")
  111.  
  112. ;;;###autoload
  113. (defvar dired-keep-marker-move t
  114.   ;; Use t as default so that moved files `take their markers with them'
  115.   "If t, moved marked files are marked if their originals were.
  116. If a character, those files (marked or not) are marked with that character.")
  117.  
  118. ;;;###autoload
  119. (defvar dired-keep-marker-copy ?C
  120.     "If t, copied files are marked if their source files were.
  121. If a character, those files are always marked with that character.")
  122.  
  123. ;;;###autoload
  124. (defvar dired-keep-marker-hardlink ?H
  125.     "If t, hard-linked files are marked if the linked-to files were.
  126. If a character, those files are always marked with that character.")
  127.  
  128. ;;;###autoload
  129. (defvar dired-keep-marker-symlink ?Y
  130.     "If t, symlinked marked files are marked if the linked-to files were.
  131. If a character, those files are always marked with that character.")
  132.  
  133. ;;;###autoload
  134. (defvar dired-dwim-target nil
  135.   "*If non-nil, dired tries to guess a default target directory:
  136. If there is a dired buffer displayed in the next window, use
  137. its current subdir, instead of the current subdir of this dired
  138. buffer.
  139.  
  140. The target is used in the prompt for file copy, move etc.")
  141.  
  142. ;;;###autoload
  143. (defvar dired-copy-preserve-time nil
  144.   "*If non-nil, Dired preserves the last-modified time in a file copy.
  145. \(This works on only some systems.)\\<dired-mode-map>
  146. Use `\\[dired-do-copy]' with a zero prefix argument to toggle its value.")
  147.  
  148. ;;; Hook variables
  149.  
  150. (defvar dired-load-hook nil
  151.   "Run after loading dired.
  152. You can customize key bindings or load extensions with this.")
  153.  
  154. (defvar dired-mode-hook nil
  155.   "Run at the very end of dired-mode.")
  156.  
  157. (defvar dired-before-readin-hook nil
  158.   "This hook is run before a dired buffer is newly read in (created or reverted).")
  159.  
  160. (defvar dired-after-readin-hook nil
  161.   "After each listing of a file or directory, this hook is run
  162. with the buffer narrowed to the listing.")
  163. ;; Note this can't simply be run inside function dired-ls as the hook
  164. ;; functions probably depend on the dired-subdir-alist to be OK.
  165.  
  166. ;;; Internal variables
  167.  
  168. (defvar dired-marker-char ?*        ; the answer is 42
  169.   ;; so that you can write things like
  170.   ;; (let ((dired-marker-char ?X))
  171.   ;;    ;; great code using X markers ...
  172.   ;;    )
  173.   ;; For example, commands operating on two sets of files, A and B.
  174.   ;; Or marking files with digits 0-9.  This could implicate
  175.   ;; concentric sets or an order for the marked files.
  176.   ;; The code depends on dynamic scoping on the marker char.
  177.   "In dired, character used to mark files for later commands.")
  178.  
  179. (defvar dired-del-marker ?D
  180.   "Character used to flag files for deletion.")
  181.  
  182. (defvar dired-shrink-to-fit
  183.   (if (fboundp 'baud-rate) (> (baud-rate) search-slow-speed) t)
  184.   "Whether dired shrinks the display buffer to fit the marked files.")
  185.  
  186. (defvar dired-flagging-regexp nil);; Last regexp used to flag files.
  187.  
  188. (defvar dired-directory nil
  189.   "The directory name or shell wildcard passed as argument to ls.
  190. Local to each dired buffer.")
  191.  
  192. (defvar dired-actual-switches nil
  193.   "The actual (buffer-local) value of `dired-listing-switches'.")
  194.  
  195. (defvar dired-re-inode-size "[0-9 \t]*"
  196.   "Regexp for optional initial inode and file size as produced by ls' -i and -s flags.")
  197.  
  198. ;; These regexps must be tested at beginning-of-line, but are also
  199. ;; used to search for next matches, so neither omitting "^" nor
  200. ;; replacing "^" by "\n" (to make it slightly faster) will work.
  201.  
  202. (defvar dired-re-mark "^[^ \n]")
  203. ;; "Regexp matching a marked line.
  204. ;; Important: the match ends just after the marker."
  205. (defvar dired-re-maybe-mark "^. ")
  206. ;; Note that dired-re-inode-size allows for an arbitray amount of
  207. ;; whitespace, making nested indentation in dired-nstd.el work.
  208. (defvar dired-re-dir (concat dired-re-maybe-mark dired-re-inode-size "d"))
  209. (defvar dired-re-sym (concat dired-re-maybe-mark dired-re-inode-size "l"))
  210. (defvar dired-re-exe;; match ls permission string of an executable file
  211.   (mapconcat (function
  212.           (lambda (x)
  213.         (concat dired-re-maybe-mark dired-re-inode-size x)))
  214.          '("-[-r][-w][xs][-r][-w].[-r][-w]."
  215.            "-[-r][-w].[-r][-w][xs][-r][-w]."
  216.            "-[-r][-w].[-r][-w].[-r][-w][xst]")
  217.          "\\|"))
  218. (defvar dired-re-dot "^.* \\.\\.?/?$")    ; with -F, might end in `/'
  219.  
  220. (defvar dired-subdir-alist nil
  221.   "Association list of subdirectories and their buffer positions:
  222.  
  223.   \((LASTDIR . LASTMARKER) ... (DEFAULT-DIRECTORY . FIRSTMARKER)).")
  224.  
  225. (defvar dired-subdir-regexp "^. \\([^ \n\r]+\\)\\(:\\)[\n\r]"
  226.   "Regexp matching a maybe hidden subdirectory line in ls -lR output.
  227. Subexpression 1 is the subdirectory proper, no trailing colon.
  228. The match starts at the beginning of the line and ends after the end
  229. of the line (\\n or \\r).
  230. Subexpression 2 must end right before the \\n or \\r.")
  231.  
  232.  
  233. ;;; Macros must be defined before they are used - for the byte compiler.
  234.  
  235. ;; Returns the count if any work was done, nil otherwise.
  236. (defmacro dired-mark-if (predicate msg)
  237.   (` (let (buffer-read-only count)
  238.        (save-excursion
  239.      (setq count 0)
  240.      (if (, msg) (message "Marking %ss..." (, msg)))
  241.      (goto-char (point-min))
  242.      (while (not (eobp))
  243.        (if (, predicate)
  244.            (progn
  245.          (delete-char 1)
  246.          (insert dired-marker-char)
  247.          (setq count (1+ count))))
  248.        (forward-line 1))
  249.      (if (, msg) (message "%s %s%s %s%s."
  250.               count
  251.               (, msg)
  252.               (dired-plural-s count)
  253.               (if (eq dired-marker-char ?\040) "un" "")
  254.               (if (eq dired-marker-char dired-del-marker)
  255.                   "flagged" "marked"))))
  256.        (and (> count 0) count))))
  257.  
  258. (defmacro dired-mark-map (body arg &optional show-progress)
  259. ;;  "Macro: Perform BODY with point somewhere on each marked line
  260. ;;and return a list of BODY's results.
  261. ;;If no marked file could be found, execute BODY on the current line.
  262. ;;  If ARG is an integer, use the next ARG (or previous -ARG, if ARG<0)
  263. ;;  files instead of the marked files.
  264. ;;  In that case point is dragged along.  This is so that commands on
  265. ;;  the next ARG (instead of the marked) files can be chained easily.
  266. ;;  If ARG is otherwise non-nil, use current file instead.
  267. ;;If optional third arg SHOW-PROGRESS evaluates to non-nil,
  268. ;;   redisplay the dired buffer after each file is processed.
  269. ;;No guarantee is made about the position on the marked line.
  270. ;;  BODY must ensure this itself if it depends on this.
  271. ;;Search starts at the beginning of the buffer, thus the car of the list
  272. ;;  corresponds to the line nearest to the buffer's bottom.  This
  273. ;;  is also true for (positive and negative) integer values of ARG.
  274. ;;BODY should not be too long as it is expanded four times."
  275. ;;
  276. ;;Warning: BODY must not add new lines before point - this may cause an
  277. ;;endless loop.
  278. ;;This warning should not apply any longer, sk  2-Sep-1991 14:10.
  279.   (` (prog1
  280.      (let (buffer-read-only case-fold-search found results)
  281.        (if (, arg)
  282.            (if (integerp (, arg))
  283.            (progn;; no save-excursion, want to move point.
  284.              (dired-repeat-over-lines
  285.               (, arg)
  286.               (function (lambda ()
  287.                   (if (, show-progress) (sit-for 0))
  288.                   (setq results (cons (, body) results)))))
  289.              (if (< (, arg) 0)
  290.              (nreverse results)
  291.                results))
  292.          ;; non-nil, non-integer ARG means use current file:
  293.          (list (, body)))
  294.          (let ((regexp (dired-marker-regexp)) next-position)
  295.            (save-excursion
  296.          (goto-char (point-min))
  297.          ;; remember position of next marked file before BODY
  298.          ;; can insert lines before the just found file,
  299.          ;; confusing us by finding the same marked file again
  300.          ;; and again and...
  301.          (setq next-position (and (re-search-forward regexp nil t)
  302.                       (point-marker))
  303.                found (not (null next-position)))
  304.          (while next-position
  305.            (goto-char next-position)
  306.            (if (, show-progress) (sit-for 0))
  307.            (setq results (cons (, body) results))
  308.            ;; move after last match
  309.            (goto-char next-position)
  310.            (forward-line 1)
  311.            (set-marker next-position nil)
  312.            (setq next-position (and (re-search-forward regexp nil t)
  313.                         (point-marker)))))
  314.            (if found
  315.            results
  316.          (list (, body))))))
  317.        ;; save-excursion loses, again
  318.        (dired-move-to-filename))))
  319.  
  320. (defun dired-mark-get-files (&optional localp arg)
  321.   "Return the marked files as list of strings.
  322. The list is in the same order as the buffer, that is, the car is the
  323.   first marked file.
  324. Values returned are normally absolute pathnames.
  325. Optional arg LOCALP as in `dired-get-filename'.
  326. Optional second argument ARG forces to use other files.  If ARG is an
  327.   integer, use the next ARG files.  If ARG is otherwise non-nil, use
  328.   current file.  Usually ARG comes from the current prefix arg."
  329.   (nreverse (save-excursion (dired-mark-map (dired-get-filename localp) arg))))
  330.  
  331.  
  332. ;; Function dired-ls is redefinable for VMS, ange-ftp, Prospero or
  333. ;; other special applications.
  334.  
  335. ;; dired-ls
  336. ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
  337. ;;   FULL-DIRECTORY-P is nil.
  338. ;;   The single line of output must display FILE's name as it was
  339. ;;   given, namely, an absolute path name.
  340. ;; - must insert exactly one line for each file if WILDCARD or
  341. ;;   FULL-DIRECTORY-P is t, plus one optional "total" line
  342. ;;   before the file lines, plus optional text after the file lines.
  343. ;;   Lines are delimited by "\n", so filenames containing "\n" are not
  344. ;;   allowed.
  345. ;;   File lines should display the basename, not a path name.
  346. ;; - must drag point after inserted text
  347. ;; - must be consistent with
  348. ;;   - functions dired-move-to-filename, (these two define what a file line is)
  349. ;;            dired-move-to-end-of-filename,
  350. ;;         dired-between-files, (shortcut for (not (dired-move-to-filename)))
  351. ;;            dired-insert-headerline
  352. ;;            dired-after-subdir-garbage (defines what a "total" line is)
  353. ;;   - variables dired-subdir-regexp
  354. (defun dired-ls (file switches &optional wildcard full-directory-p)
  355. ;  "Insert ls output of FILE, formatted according to SWITCHES.
  356. ;Optional third arg WILDCARD means treat FILE as shell wildcard.
  357. ;Optional fourth arg FULL-DIRECTORY-P means file is a directory and
  358. ;switches do not contain `d', so that a full listing is expected.
  359. ;
  360. ;Uses dired-ls-program (and shell-file-name if WILDCARD) to do the work."
  361.   (if wildcard
  362.       (let ((default-directory (file-name-directory file)))
  363.     (call-process shell-file-name nil t nil
  364.               "-c" (concat dired-ls-program " -d " switches " "
  365.                    (file-name-nondirectory file))))
  366.     (call-process dired-ls-program nil t nil switches file)))
  367.  
  368. ;; The dired command
  369.  
  370. (defun dired-read-dir-and-switches (str)
  371.   ;; For use in interactive.
  372.   (reverse (list
  373.         (if current-prefix-arg
  374.         (read-string "Dired listing switches: "
  375.                  dired-listing-switches))
  376.         (read-file-name (format "Dired %s(directory): " str)
  377.                 nil default-directory nil))))
  378.  
  379. ;;;###autoload (define-key ctl-x-map "d" 'dired)
  380. ;;;###autoload
  381. (defun dired (dirname &optional switches)
  382.   "\"Edit\" directory DIRNAME--delete, rename, print, etc. some files in it.
  383. With an optional prefix argument you can specify the ls SWITCHES that are used.
  384. Dired displays a list of files in DIRNAME (which may also have
  385.   shell wildcards appended to select certain files).
  386. You can move around in it with the usual commands.
  387. You can flag files for deletion with \\<dired-mode-map>\\[dired-flag-file-deleted] and then delete them by
  388.   typing \\[dired-do-deletions].
  389. Type \\[describe-mode] after entering dired for more info.
  390.  
  391. If DIRNAME is already in a dired buffer, that buffer is used without refresh."
  392.   ;; Cannot use (interactive "D") because of wildcards.
  393.   (interactive (dired-read-dir-and-switches ""))
  394.   (switch-to-buffer (dired-noselect dirname switches)))
  395.  
  396. ;;;###autoload (define-key ctl-x-4-map "d" 'dired-other-window)
  397. ;;;###autoload
  398. (defun dired-other-window (dirname &optional switches)
  399.   "\"Edit\" directory DIRNAME.  Like `dired' but selects in another window."
  400.   (interactive (dired-read-dir-and-switches "in other window "))
  401.   (switch-to-buffer-other-window (dired-noselect dirname switches)))
  402.  
  403. ;;;###autoload
  404. (defun dired-noselect (dirname &optional switches)
  405.   "Like `dired' but returns the dired buffer as value, does not select it."
  406.   (or dirname (setq dirname default-directory))
  407.   ;; This loses the distinction between "/foo/*/" and "/foo/*" that
  408.   ;; some shells make:
  409.   (setq dirname (expand-file-name (directory-file-name dirname)))
  410.   (if (file-directory-p dirname)
  411.       (setq dirname (file-name-as-directory dirname)))
  412.   (dired-internal-noselect dirname switches))
  413.  
  414. ;; Separate function from dired-noselect for the sake of dired-vms.el.
  415. (defun dired-internal-noselect (dirname &optional switches)
  416.   ;; If there is an existing dired buffer for DIRNAME, just leave
  417.   ;; buffer as it is (don't even call dired-revert).
  418.   ;; This saves time especially for deep trees or with ange-ftp.
  419.   ;; The user can type `g'easily, and it is more consistent with find-file.
  420.   ;; But if SWITCHES are given they are probably different from the
  421.   ;; buffer's old value, so call dired-sort-other, which does
  422.   ;; revert the buffer.
  423.   ;; A pity we can't possibly do "Directory has changed - refresh? "
  424.   ;; like find-file does...maybe in the GNU OS.
  425.   (let* ((buffer (dired-find-buffer-nocreate dirname))
  426.      ;; note that buffer already is in dired-mode, if found
  427.      (new-buffer-p (not buffer))
  428.      (old-buf (current-buffer)))
  429.     (or buffer
  430.     (let ((default-major-mode 'fundamental-mode))
  431.       ;; We don't want default-major-mode to run hooks and set auto-fill
  432.       ;; or whatever, now that dired-mode does not
  433.       ;; kill-all-local-variables any longer.
  434.       (setq buffer (create-file-buffer (directory-file-name dirname)))))
  435.     (set-buffer buffer)
  436.     (if (not new-buffer-p)        ; existing buffer ...
  437.     (if switches            ; ... but new switches
  438.         (dired-sort-other switches))    ; this calls dired-revert
  439.       ;; Else a new buffer
  440.       (setq default-directory (if (file-directory-p dirname)
  441.                   dirname
  442.                 (file-name-directory dirname)))
  443.       (or switches (setq switches dired-listing-switches))
  444.       (dired-mode dirname switches)
  445.       ;; default-directory and dired-actual-switches are set now
  446.       ;; (buffer-local), so we can call dired-readin:
  447.       (let ((failed t))
  448.     (unwind-protect
  449.         (progn (dired-readin dirname buffer)
  450.            (setq failed nil))
  451.       ;; dired-readin can fail if parent directories are inaccessible.
  452.       ;; Don't leave an empty buffer around in that case.
  453.       (if failed (kill-buffer buffer))))
  454.       ;; No need to narrow since the whole buffer contains just
  455.       ;; dired-readin's output, nothing else.  The hook can
  456.       ;; successfully use dired functions (e.g. dired-get-filename)
  457.       ;; as the subdir-alist has been built in dired-readin.
  458.       (run-hooks 'dired-after-readin-hook)
  459.       (goto-char (point-min))
  460.       (dired-initial-position dirname))
  461.     (set-buffer old-buf)
  462.     buffer))
  463.  
  464. ;; This differs from dired-buffers-for-dir in that it does not consider
  465. ;; subdirs of default-directory and searches for the first match only
  466. (defun dired-find-buffer-nocreate (dirname)
  467.   (let (found (blist (buffer-list)))
  468.     (while blist
  469.       (save-excursion
  470.         (set-buffer (car blist))
  471.     (if (and (eq major-mode 'dired-mode)
  472.          (equal dired-directory dirname))
  473.         (setq found (car blist)
  474.           blist nil)
  475.       (setq blist (cdr blist)))))
  476.     found))
  477.  
  478.  
  479. ;; Read in a new dired buffer
  480.  
  481. ;; dired-readin differs from dired-insert-subdir in that it accepts
  482. ;; wildcards, erases the buffer, and builds the subdir-alist anew
  483. ;; (including making it buffer-local and clearing it first).
  484. (defun dired-readin (dirname buffer)
  485.   ;; default-directory and dired-actual-switches must be buffer-local
  486.   ;; and initialized by now.
  487.   ;; Thus we can test (equal default-directory dirname) instead of
  488.   ;; (file-directory-p dirname) and save a filesystem transaction.
  489.   ;; Also, we can run this hook which may want to modify the switches
  490.   ;; based on default-directory, e.g. with ange-ftp to a SysV host
  491.   ;; where ls won't understand -Al switches.
  492.   (setq dirname (expand-file-name dirname))
  493.   (run-hooks 'dired-before-readin-hook)
  494.   (save-excursion
  495.     (message "Reading directory %s..." dirname)
  496.     (set-buffer buffer)
  497.     (let (buffer-read-only)
  498.       (widen)
  499.       (erase-buffer)
  500.       (dired-readin-insert dirname)
  501.       (dired-indent-rigidly (point-min) (point-max) 2)
  502.       ;; We need this to make the root dir have a header line as all
  503.       ;; other subdirs have:
  504.       (goto-char (point-min))
  505.       (dired-insert-headerline default-directory)
  506.       ;; can't run dired-after-readin-hook here, it may depend on the subdir
  507.       ;; alist to be OK.
  508.       )
  509.     (message "Reading directory %s...done" dirname)
  510.     (set-buffer-modified-p nil)
  511.     ;; Must first make alist buffer local and set it to nil because
  512.     ;; dired-build-subdir-alist will call dired-clear-alist first
  513.     (set (make-local-variable 'dired-subdir-alist) nil)
  514.     (let (case-fold-search)
  515.       (if (string-match "R" dired-actual-switches)
  516.       (dired-build-subdir-alist)
  517.     ;; no need to parse the buffer if listing is not recursive
  518.     (dired-simple-subdir-alist)))))
  519.  
  520. ;; Subroutines of dired-readin
  521.  
  522. (defun dired-readin-insert (dirname)
  523.   ;; Just insert listing for DIRNAME, assuming a clean buffer.
  524.   (let ((font-lock-mode nil))
  525.   (if (equal default-directory dirname);; i.e., (file-directory-p dirname)
  526.       (dired-ls (if (or (let (case-fold-search)
  527.               (string-match "R" dired-actual-switches))
  528.             (eq system-type 'vax-vms))
  529.             dirname
  530.           ;; On SysV derived system, symbolic links to
  531.           ;; directories are not resolved, while on BSD
  532.           ;; derived it suffices to let DIRNAME end in slash.
  533.           ;; We always let it end in "/." since it does no
  534.           ;; harm on BSD and makes Dired work on such links on
  535.           ;; SysV.
  536.           ;; Cannot do this with -R since "dir/./subdir"
  537.           ;; headerlines would result, utterly confusing dired.
  538.           (concat dirname "."))
  539.         dired-actual-switches nil t)
  540.     (if (not (file-readable-p
  541.           (directory-file-name (file-name-directory dirname))))
  542.     (error "Directory %s inaccessible or nonexistent" dirname)
  543.       ;; else assume it contains wildcards:
  544.       (dired-ls dirname dired-actual-switches t)
  545.       (save-excursion;; insert wildcard instead of total line:
  546.     (goto-char (point-min))
  547.     (insert "wildcard " (file-name-nondirectory dirname) "\n"))))))
  548.  
  549. (defun dired-insert-headerline (dir);; also used by dired-insert-subdir
  550.   ;; Insert DIR's headerline with no trailing slash, exactly like ls
  551.   ;; would, and put cursor where dired-build-subdir-alist puts subdir
  552.   ;; boundaries.
  553.   (save-excursion (insert "  " (directory-file-name dir) ":\n")))
  554.  
  555.  
  556. ;; Reverting a dired buffer
  557.  
  558. (defun dired-revert (&optional arg noconfirm)
  559.   ;; Reread the dired buffer.  Must also be called after
  560.   ;; dired-actual-switches have changed.
  561.   ;; Should not fail even on completely garbaged buffers.
  562.   ;; Preserves old cursor, marks/flags, hidden-p.
  563.   (widen)                ; just in case user narrowed
  564.   (let ((opoint (point))
  565.     (ofile (dired-get-filename nil t))
  566.     (mark-alist nil)        ; save marked files
  567.     (hidden-subdirs (dired-remember-hidden))
  568.     (old-subdir-alist (cdr (reverse dired-subdir-alist))) ; except pwd
  569.     case-fold-search        ; we check for upper case ls flags
  570.     buffer-read-only)
  571.     (goto-char (point-min))
  572.     (setq mark-alist;; only after dired-remember-hidden since this unhides:
  573.       (dired-remember-marks (point-min) (point-max)))
  574.     ;; treat top level dir extra (it may contain wildcards)
  575.     (dired-readin dired-directory (current-buffer))
  576.     (let ((dired-after-readin-hook nil))
  577.       ;; don't run that hook for each subdir...
  578.       (dired-insert-old-subdirs old-subdir-alist))
  579.     (dired-mark-remembered mark-alist)    ; mark files that were marked
  580.     ;; ... run the hook for the whole buffer, and only after markers
  581.     ;; have been reinserted (else omitting in dired-x would omit marked files)
  582.     (run-hooks 'dired-after-readin-hook)    ; no need to narrow
  583.     (or (and ofile (dired-goto-file ofile)) ; move cursor to where it
  584.     (goto-char opoint))        ; was before
  585.     (dired-move-to-filename)
  586.     (save-excursion            ; hide subdirs that were hidden
  587.       (mapcar (function (lambda (dir)
  588.               (if (dired-goto-subdir dir)
  589.                   (dired-hide-subdir 1))))
  590.           hidden-subdirs)))
  591.   ;; outside of the let scope
  592.   (setq buffer-read-only t))
  593.  
  594. ;; Subroutines of dired-revert
  595. ;; Some of these are also used when inserting subdirs.
  596.  
  597. (defun dired-remember-marks (beg end)
  598.   ;; Return alist of files and their marks, from BEG to END.
  599.   (if selective-display            ; must unhide to make this work.
  600.       (let (buffer-read-only)
  601.     (subst-char-in-region beg end ?\r ?\n)))
  602.   (let (fil chr alist)
  603.     (save-excursion
  604.       (goto-char beg)
  605.       (while (re-search-forward dired-re-mark end t)
  606.     (if (setq fil (dired-get-filename nil t))
  607.         (setq chr (preceding-char)
  608.           alist (cons (cons fil chr) alist)))))
  609.     alist))
  610.  
  611. (defun dired-mark-remembered (alist)
  612.   ;; Mark all files remembered in ALIST.
  613.   (let (elt fil chr)
  614.     (while alist
  615.       (setq elt (car alist)
  616.         alist (cdr alist)
  617.         fil (car elt)
  618.         chr (cdr elt))
  619.       (if (dired-goto-file fil)
  620.       (save-excursion
  621.         (beginning-of-line)
  622.         (delete-char 1)
  623.         (insert chr))))))
  624.  
  625. (defun dired-remember-hidden ()
  626.   (let ((l dired-subdir-alist) dir result)
  627.     (while l
  628.       (setq dir (car (car l))
  629.         l (cdr l))
  630.       (if (dired-subdir-hidden-p dir)
  631.       (setq result (cons dir result))))
  632.     result))
  633.  
  634. (defun dired-insert-old-subdirs (old-subdir-alist)
  635.   ;; Try to insert all subdirs that were displayed before
  636.   (or (string-match "R" dired-actual-switches)
  637.       (let (elt dir)
  638.     (while old-subdir-alist
  639.       (setq elt (car old-subdir-alist)
  640.         old-subdir-alist (cdr old-subdir-alist)
  641.         dir (car elt))
  642.       (condition-case ()
  643.           (dired-insert-subdir dir)
  644.         (error nil))))))
  645.  
  646.  
  647. ;; dired mode key bindings and initialization
  648.  
  649. (defvar dired-mode-map nil "Local keymap for dired-mode buffers.")
  650. (if dired-mode-map
  651.     nil
  652.   ;; Force `f' rather than `e' in the mode doc:
  653.   (fset 'dired-advertised-find-file 'dired-find-file)
  654.   ;; This looks ugly when substitute-command-keys uses C-d instead d:
  655.   ;;  (define-key dired-mode-map "\C-d" 'dired-flag-file-deleted)
  656.  
  657.   (setq dired-mode-map (make-keymap))
  658.   (suppress-keymap dired-mode-map)
  659.   ;; Commands to mark certain categories of files
  660.   (define-key dired-mode-map "#" 'dired-flag-auto-save-files)
  661.   (define-key dired-mode-map "*" 'dired-mark-executables)
  662.   (define-key dired-mode-map "." 'dired-clean-directory)
  663.   (define-key dired-mode-map "/" 'dired-mark-directories)
  664.   (define-key dired-mode-map "@" 'dired-mark-symlinks)
  665.   ;; Upper case keys (except !, c, r) for operating on the marked files
  666.   (define-key dired-mode-map "c" 'dired-do-copy)
  667.   (define-key dired-mode-map "r" 'dired-do-move)
  668.   (define-key dired-mode-map "!" 'dired-do-shell-command)
  669.   (define-key dired-mode-map "B" 'dired-do-byte-compile)
  670.   (define-key dired-mode-map "C" 'dired-do-compress)
  671.   (define-key dired-mode-map "G" 'dired-do-chgrp)
  672.   (define-key dired-mode-map "H" 'dired-do-hardlink)
  673.   (define-key dired-mode-map "L" 'dired-do-load)
  674.   (define-key dired-mode-map "M" 'dired-do-chmod)
  675.   (define-key dired-mode-map "O" 'dired-do-chown)
  676.   (define-key dired-mode-map "P" 'dired-do-print)
  677.   (define-key dired-mode-map "U" 'dired-do-uncompress)
  678.   (define-key dired-mode-map "X" 'dired-do-delete)
  679.   (define-key dired-mode-map "Y" 'dired-do-symlink)
  680.   ;; exceptions to the upper key rule
  681.   (define-key dired-mode-map "D" 'dired-diff)
  682.   (define-key dired-mode-map "W" 'dired-why)
  683.   ;; Tree Dired commands
  684.   (define-key dired-mode-map "\M-\C-?" 'dired-unflag-all-files)
  685.   (define-key dired-mode-map "\M-\C-d" 'dired-tree-down)
  686.   (define-key dired-mode-map "\M-\C-u" 'dired-tree-up)
  687.   (define-key dired-mode-map "\M-\C-n" 'dired-next-subdir)
  688.   (define-key dired-mode-map "\M-\C-p" 'dired-prev-subdir)
  689.   ;; move to marked files
  690.   (define-key dired-mode-map "\M-{" 'dired-prev-marked-file)
  691.   (define-key dired-mode-map "\M-}" 'dired-next-marked-file)
  692.   ;; kill marked files
  693.   (define-key dired-mode-map "\M-k" 'dired-do-kill)
  694.   ;; Make all regexp commands share a `%' prefix:
  695.   (fset 'dired-regexp-prefix (make-sparse-keymap))
  696.   (define-key dired-mode-map "%" 'dired-regexp-prefix)
  697.   (define-key dired-mode-map "%u" 'dired-upcase)
  698.   (define-key dired-mode-map "%l" 'dired-downcase)
  699.   (define-key dired-mode-map "%d" 'dired-flag-regexp-files)
  700.   (define-key dired-mode-map "%m" 'dired-mark-files-regexp)
  701.   (define-key dired-mode-map "%r" 'dired-do-rename-regexp)
  702.   (define-key dired-mode-map "%c" 'dired-do-copy-regexp)
  703.   (define-key dired-mode-map "%H" 'dired-do-hardlink-regexp)
  704.   (define-key dired-mode-map "%Y" 'dired-do-symlink-regexp)
  705.   ;; Lower keys for commands not operating on all the marked files
  706.   (define-key dired-mode-map "d" 'dired-flag-file-deleted)
  707.   (define-key dired-mode-map "e" 'dired-find-file)
  708.   (define-key dired-mode-map "f" 'dired-advertised-find-file)
  709.   (define-key dired-mode-map "g" 'revert-buffer)
  710.   (define-key dired-mode-map "h" 'describe-mode)
  711.   (define-key dired-mode-map "i" 'dired-maybe-insert-subdir)
  712.   (define-key dired-mode-map "k" 'dired-kill-line-or-subdir)
  713.   (define-key dired-mode-map "l" 'dired-do-redisplay)
  714.   (define-key dired-mode-map "m" 'dired-mark-subdir-or-file)
  715.   (define-key dired-mode-map "n" 'dired-next-line)
  716.   (define-key dired-mode-map "o" 'dired-find-file-other-window)
  717.   (define-key dired-mode-map "p" 'dired-previous-line)
  718.   (define-key dired-mode-map "q" 'dired-quit)
  719.   (define-key dired-mode-map "s" 'dired-sort-toggle-or-edit)
  720.   (define-key dired-mode-map "u" 'dired-unmark-subdir-or-file)
  721.   (define-key dired-mode-map "v" 'dired-view-file)
  722.   (define-key dired-mode-map "x" 'dired-do-deletions)
  723.   (define-key dired-mode-map "~" 'dired-flag-backup-files)
  724.   (define-key dired-mode-map "\M-~" 'dired-backup-diff)
  725.   (define-key dired-mode-map "+" 'dired-create-directory)
  726.   ;; moving
  727.   (define-key dired-mode-map "<" 'dired-prev-dirline)
  728.   (define-key dired-mode-map ">" 'dired-next-dirline)
  729.   (define-key dired-mode-map "^" 'dired-up-directory)
  730.   (define-key dired-mode-map " "  'dired-next-line)
  731.   (define-key dired-mode-map "\C-n" 'dired-next-line)
  732.   (define-key dired-mode-map "\C-p" 'dired-previous-line)
  733.   ;; hiding
  734.   (define-key dired-mode-map "$" 'dired-hide-subdir)
  735.   (define-key dired-mode-map "=" 'dired-hide-all)
  736.   ;; misc
  737.   (define-key dired-mode-map "?" 'dired-summary)
  738.   (define-key dired-mode-map "\177" 'dired-backup-unflag)
  739.   (define-key dired-mode-map "\C-_" 'dired-undo)
  740.   (define-key dired-mode-map "\C-xu" 'dired-undo)
  741.   )
  742.  
  743. (or (equal (assq 'dired-sort-mode minor-mode-alist)
  744.        '(dired-sort-mode dired-sort-mode))
  745.     ;; Test whether this has already been done in case dired is reloaded
  746.     ;; There may be several elements with dired-sort-mode as car.
  747.     (setq minor-mode-alist
  748.       (cons '(dired-sort-mode dired-sort-mode)
  749.         ;; dired-sort-mode is nil outside dired
  750.         minor-mode-alist)))
  751.  
  752. ;; Dired mode is suitable only for specially formatted data.
  753. (put 'dired-mode 'mode-class 'special)
  754.  
  755. (defun dired-mode (&optional dirname switches)
  756.   "\
  757. Mode for \"editing\" directory listings.
  758. In dired, you are \"editing\" a list of the files in a directory and
  759.   \(optionally) its subdirectories, in the format of `ls -lR'.
  760.   Each directory is a page: use \\[backward-page] and \\[forward-page] to move pagewise.
  761. \"Editing\" means that you can run shell commands on files, visit,
  762.   compress, load or byte-compile them, change their file attributes
  763.   and insert subdirectories into the same buffer.  You can \"mark\"
  764.   files for later commands or \"flag\" them for deletion, either file
  765.   by file or all files matching certain criteria.
  766. You can move using the usual cursor motion commands.\\<dired-mode-map>
  767. Letters no longer insert themselves.  Digits are prefix arguments.
  768. Instead, type \\[dired-flag-file-deleted] to flag a file for Deletion.
  769. Type \\[dired-mark-subdir-or-file] to Mark a file or subdirectory for later commands.
  770.   Most commands operate on the marked files and use the current file
  771.   if no files are marked.  Use a numeric prefix argument to operate on
  772.   the next ARG (or previous -ARG if ARG<0) files, or just `1'
  773.   to operate on the current file only.  Prefix arguments override marks.
  774.   Mark-using commands display a list of failures afterwards.  Type \\[dired-why] to see
  775.   why something went wrong.
  776. Type \\[dired-unmark-subdir-or-file] to Unmark a file or all files of a subdirectory.
  777. Type \\[dired-backup-unflag] to back up one line and unflag.
  778. Type \\[dired-do-deletions] to eXecute the deletions requested.
  779. Type \\[dired-advertised-find-file] to Find the current line's file
  780.   (or dired it in another buffer, if it is a directory).
  781. Type \\[dired-find-file-other-window] to find file or dired directory in Other window.
  782. Type \\[dired-maybe-insert-subdir] to Insert a subdirectory in this buffer.
  783. Type \\[dired-do-move] to Rename a file or move the marked files to another directory.
  784. Type \\[dired-do-copy] to Copy files.
  785. Type \\[dired-sort-toggle-or-edit] to toggle sorting by name/date or change the ls switches.
  786. Type \\[revert-buffer] to read all currently expanded directories again.
  787.   This retains all marks and hides subdirs again that were hidden before.
  788. SPC and DEL can be used to move down and up by lines.
  789.  
  790. If dired ever gets confused, you can either type \\[revert-buffer] \
  791. to read the
  792. directories again, type \\[dired-do-redisplay] \
  793. to relist a single or the marked files or a
  794. subdirectory, or type \\[dired-build-subdir-alist] to parse the buffer
  795. again for the directory tree.
  796.  
  797. Customization variables (rename this buffer and type \\[describe-variable] on each line
  798. for more info):
  799.  
  800.   dired-listing-switches
  801.   dired-trivial-filenames
  802.   dired-shrink-to-fit
  803.   dired-marker-char
  804.   dired-del-marker
  805.   dired-keep-marker-move
  806.   dired-keep-marker-copy
  807.   dired-keep-marker-hardlink
  808.   dired-keep-marker-symlink
  809.  
  810. Hooks (use \\[describe-variable] to see their documentation):
  811.  
  812.   dired-before-readin-hook
  813.   dired-after-readin-hook
  814.   dired-mode-hook
  815.   dired-load-hook
  816.  
  817. Keybindings:
  818. \\{dired-mode-map}"
  819.   ;; Not to be called interactively (e.g. dired-directory will be set
  820.   ;; to default-directory, which is wrong with wildcards).
  821.   (kill-all-local-variables)
  822.   (use-local-map dired-mode-map)
  823.   (dired-advertise)            ; default-directory is already set
  824.   (setq major-mode 'dired-mode
  825.     mode-name "Dired"
  826.     case-fold-search nil
  827.     buffer-read-only t
  828.     selective-display t        ; for subdirectory hiding
  829.     modeline-buffer-identification '("Dired: %17b"))
  830.   (set (make-local-variable 'revert-buffer-function)
  831.        (function dired-revert))
  832.   (set (make-local-variable 'page-delimiter)
  833.        "\n\n")
  834.   (set (make-local-variable 'dired-directory)
  835.        (or dirname default-directory))
  836.   (set (make-local-variable 'list-buffers-directory)
  837.        dired-directory)
  838.   (set (make-local-variable 'dired-actual-switches)
  839.        (or switches dired-listing-switches))
  840.   (make-local-variable 'dired-sort-mode)
  841.   (dired-sort-other dired-actual-switches t)
  842.   (run-hooks 'dired-mode-hook))
  843.  
  844.  
  845. (defun dired-check-ls-l ()
  846.   (let (case-fold-search)
  847.     (or (string-match "l" dired-actual-switches)
  848.     (error "Dired needs -l in ls switches"))))
  849.  
  850. (defun dired-repeat-over-lines (arg function)
  851.   ;; This version skips non-file lines.
  852.   (beginning-of-line)
  853.   (while (and (> arg 0) (not (eobp)))
  854.     (setq arg (1- arg))
  855.     (beginning-of-line)
  856.     (while (and (not (eobp)) (dired-between-files)) (forward-line 1))
  857.     (save-excursion (funcall function))
  858.     (forward-line 1))
  859.   (while (and (< arg 0) (not (bobp)))
  860.     (setq arg (1+ arg))
  861.     (forward-line -1)
  862.     (while (and (not (bobp)) (dired-between-files)) (forward-line -1))
  863.     (beginning-of-line)
  864.     (save-excursion (funcall function))
  865.     (dired-move-to-filename))
  866.   (dired-move-to-filename))
  867.  
  868. (defun dired-flag-file-deleted (arg)
  869.   "In dired, flag the current line's file for deletion.
  870. With prefix arg, repeat over several lines.
  871.  
  872. If on a subdir headerline, mark all its files except `.' and `..'."
  873.   (interactive "P")
  874.   (let ((dired-marker-char dired-del-marker))
  875.     (dired-mark-subdir-or-file arg)))
  876.  
  877. (defun dired-quit ()
  878.   "Bury the current dired buffer."
  879.   (interactive)
  880.   (bury-buffer))
  881.  
  882. (defun dired-summary ()
  883.   (interactive)
  884.   ;>> this should check the key-bindings and use substitute-command-keys if non-standard
  885.   (message
  886.    "d-elete, u-ndelete, x-punge, f-ind, o-ther window, r-ename, c-opy, h-elp"))
  887.  
  888. (defun dired-create-directory (directory)
  889.   "Create a directory called DIRECTORY."
  890.   (interactive
  891.    (list (read-file-name "Create directory: " (dired-current-directory))))
  892.   (let ((expanded (directory-file-name (expand-file-name directory))))
  893.     (make-directory expanded)
  894.     (dired-add-file expanded)
  895.     (dired-move-to-filename)))
  896.  
  897. (defun dired-undo ()
  898.   "Undo in a dired buffer.
  899. This doesn't recover lost files, it is just normal undo with temporarily
  900. writeable buffer.  You can use it to recover marks, killed lines or subdirs.
  901. In the latter case, you have to do \\[dired-build-subdir-alist] to
  902. parse the buffer again."
  903.   (interactive)
  904.   (let (buffer-read-only)
  905.     (undo)))
  906.  
  907. (defun dired-unflag (arg)
  908.   "In dired, remove the current line's delete flag then move to next line.
  909. Optional prefix ARG says how many lines to unflag."
  910.   (interactive "p")
  911.   (dired-repeat-over-lines arg
  912.     '(lambda ()
  913.        (let (buffer-read-only)
  914.      (delete-char 1)
  915.      (insert " ")
  916.      (forward-char -1)
  917.      nil))))
  918.  
  919. (defun dired-backup-unflag (arg)
  920.   "In dired, move up lines and remove deletion flag there.
  921. Optional prefix ARG says how many lines to unflag; default is one line."
  922.   (interactive "p")
  923.   (dired-unflag (- arg)))
  924.  
  925. (defun dired-next-line (arg)
  926.   "Move down lines then position at filename.
  927. Optional prefix ARG says how many lines to move; default is one line."
  928.   (interactive "_p")
  929.   (next-line arg)
  930.   (dired-move-to-filename))
  931.  
  932. (defun dired-previous-line (arg)
  933.   "Move up lines then position at filename.
  934. Optional prefix ARG says how many lines to move; default is one line."
  935.   (interactive "_p")
  936.   (previous-line arg)
  937.   (dired-move-to-filename))
  938.  
  939. (defun dired-up-directory ()
  940.   "Run dired on parent directory of current directory.
  941. Find the parent directory either in this buffer or another buffer.
  942. Creates a buffer if necessary."
  943.   (interactive)
  944.   (let* ((dir (dired-current-directory))
  945.      (up (file-name-directory (directory-file-name dir))))
  946.     (or (dired-goto-file (directory-file-name dir))
  947.     (dired-goto-subdir up)
  948.     (progn
  949.       (dired up)
  950.       (dired-goto-file dir)))))
  951.  
  952. (defun dired-find-file ()
  953.   "In dired, visit the file or directory named on this line."
  954.   (interactive)
  955.   (let ((find-file-run-dired t))
  956.     (find-file (dired-get-filename))))
  957.  
  958. (defun dired-view-file ()
  959.   "In dired, examine a file in view mode, returning to dired when done.
  960. When file is a directory, show it in this buffer if it is inserted;
  961. otherwise, display it in another buffer."
  962.   (interactive)
  963.   (if (file-directory-p (dired-get-filename))
  964.       (or (dired-goto-subdir (dired-get-filename))
  965.       (dired (dired-get-filename)))
  966.     (view-file (dired-get-filename))))
  967.  
  968. (defun dired-find-file-other-window ()
  969.   "In dired, visit this file or directory in another window."
  970.   (interactive)
  971.   (let ((find-file-run-dired t)) ;; XEmacs
  972.     (find-file-other-window (dired-get-filename))))
  973.  
  974. (defun dired-get-filename (&optional localp no-error-if-not-filep)
  975.   "In dired, return name of file mentioned on this line.
  976. Value returned normally includes the directory name.
  977. Optional arg LOCALP with value `no-dir' means don't include directory
  978.   name in result.  A value of t means use path name relative to
  979.   `default-directory', which still may contain slashes if in a subdirectory.
  980. Optional arg NO-ERROR-IF-NOT-FILEP means return nil if no filename on
  981.   this line, otherwise an error occurs."
  982.   (let (case-fold-search file p1 p2)
  983.     (save-excursion
  984.       (if (setq p1 (dired-move-to-filename (not no-error-if-not-filep)))
  985.       (setq p2 (dired-move-to-end-of-filename no-error-if-not-filep))))
  986.     ;; nil if no file on this line, but no-error-if-not-filep is t:
  987.     (if (setq file (and p1 p2 (buffer-substring p1 p2)))
  988.     ;; Check if ls quoted the names, and unquote them.
  989.     ;; Using read to unquote is much faster than substituting
  990.     ;; \007 (4 chars) -> ^G  (1 char) etc. in a lisp loop.
  991.     (cond ((string-match "b" dired-actual-switches) ; System V ls
  992.            ;; This case is about 20% slower than without -b.
  993.            (setq file
  994.              (read
  995.               (concat "\""
  996.                   ;; some ls -b don't escape quotes, argh!
  997.                   ;; This is not needed for GNU ls, though.
  998.                   (or (dired-string-replace-match
  999.                    "\\([^\\]\\)\"" file "\\1\\\\\"")
  1000.                   file)
  1001.                   "\""))))
  1002.           ;; If you do this, update dired-insert-subdir-validate too
  1003.           ;; ((string-match "Q" dired-actual-switches) ; GNU ls
  1004.           ;;  (setq file (read file)))
  1005.           ))
  1006.     (if (eq localp 'no-dir)
  1007.     file
  1008.       (and file (concat (dired-current-directory localp) file)))))
  1009.  
  1010. (defun dired-move-to-filename (&optional raise-error eol)
  1011.   "In dired, move to first char of filename on this line.
  1012. Returns position (point) or nil if no filename on this line."
  1013.   ;; This is the UNIX version.
  1014.   (or eol (setq eol (progn (end-of-line) (point))))
  1015.   (beginning-of-line)
  1016.   (if (string-match "l" dired-actual-switches)
  1017.       (if (re-search-forward
  1018.        "\\(Jan\\|Feb\\|Mar\\|Apr\\|May\\|Jun\\|Jul\\|Aug\\|Sep\\|Oct\\|Nov\\|Dec\\)[ ]+[0-9]+"
  1019.        eol t)
  1020.       (progn
  1021.         (skip-chars-forward " ")    ; there is one SPC after day of month
  1022.         (skip-chars-forward "^ " eol) ; move after time of day (or year)
  1023.         (skip-chars-forward " " eol) ; there is space before the file name
  1024.         ;; Actually, if the year instead of clock time is displayed,
  1025.         ;; there are (only for some ls programs?) two spaces instead
  1026.         ;; of one before the name.
  1027.         ;; If we could depend on ls inserting exactly one SPC we
  1028.         ;; would not bomb on names _starting_ with SPC.
  1029.         (point))
  1030.     (if raise-error
  1031.         (error "No file on this line")
  1032.       nil))
  1033.     ;; else ls switches don't contain -l.
  1034.     ;; Note that even if we make dired-move-to-filename and
  1035.     ;; dired-move-to-end-of-filename (and thus dired-get-filename)
  1036.     ;; work, all commands that gleaned information from the permission
  1037.     ;; bits (like dired-mark-directories) will cease to work properly.
  1038.     (if (eolp)
  1039.     (if raise-error
  1040.         (error "No file on this line")
  1041.       nil)
  1042.       ;; skip marker, if any
  1043.       (forward-char))
  1044.     (skip-chars-forward " ")
  1045.     (point)))
  1046.  
  1047. (defun dired-move-to-end-of-filename (&optional no-error)
  1048.   ;; Assumes point is at beginning of filename,
  1049.   ;; thus the rwx bit re-search-backward below will succeed in *this*
  1050.   ;; line if at all.  So, it should be called only after
  1051.   ;; (dired-move-to-filename t).
  1052.   ;; On failure, signals an error (with non-nil NO-ERROR just returns nil).
  1053.   ;; This is the UNIX version.
  1054.   (let (opoint file-type executable symlink hidden case-fold-search used-F eol)
  1055.     ;; case-fold-search is nil now, so we can test for capital F:
  1056.     (setq used-F (string-match "F" dired-actual-switches)
  1057.       opoint (point)
  1058.           eol (save-excursion (end-of-line) (point))
  1059.       hidden (and selective-display
  1060.               (save-excursion (search-forward "\r" eol t))))
  1061.     (if hidden
  1062.     nil
  1063.       (save-excursion;; Find out what kind of file this is:
  1064.     ;; Restrict perm bits to be non-blank,
  1065.     ;; otherwise this matches one char to early (looking backward):
  1066.     ;; "l---------" (some systems make symlinks that way)
  1067.     ;; "----------" (plain file with zero perms)
  1068.     (if (re-search-backward
  1069.          "\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)"
  1070.          nil t)
  1071.         (setq file-type (char-after (match-beginning 1))
  1072.           symlink (eq file-type ?l)
  1073.           ;; Only with -F we need to know whether it's an executable
  1074.           executable (and
  1075.                   used-F
  1076.                   (string-match
  1077.                    "[xst]";; execute bit set anywhere?
  1078.                    (concat
  1079.                 (buffer-substring (match-beginning 2)
  1080.                           (match-end 2))
  1081.                 (buffer-substring (match-beginning 3)
  1082.                           (match-end 3))
  1083.                 (buffer-substring (match-beginning 4)
  1084.                           (match-end 4))))))
  1085.       (or no-error
  1086.           (not (string-match "l" dired-actual-switches))
  1087.           (error "No file on this line"))))
  1088.       ;; Move point to end of name:
  1089.       (if symlink
  1090.       (if (search-forward " ->" eol t)
  1091.           (progn
  1092.         (forward-char -3)
  1093.         (and used-F
  1094.              dired-ls-F-marks-symlinks
  1095.              (eq (preceding-char) ?@);; did ls really mark the link?
  1096.              (forward-char -1))))
  1097.     (goto-char eol);; else not a symbolic link
  1098.     ;; ls -lF marks dirs, sockets and executables with exactly one
  1099.     ;; trailing character. (Executable bits on symlinks ain't mean
  1100.     ;; a thing, even to ls, but we know it's not a symlink.)
  1101.     (and used-F
  1102.          ;; -F may not actually be honored, e.g. by an FTP ls in ange-ftp
  1103.          (let ((char (preceding-char)))
  1104.            (or (and (eq file-type ?d) (eq char ?/))
  1105.            (and executable (eq char ?*))
  1106.            (and (eq file-type ?s) (eq char ?=))))
  1107.          (forward-char -1))))
  1108.     (or no-error
  1109.     (not (eq opoint (point)))
  1110.     (error (if hidden
  1111.            (substitute-command-keys
  1112.             "File line is hidden, type \\[dired-hide-subdir] to unhide")
  1113.          "No file on this line")))
  1114.     (if (eq opoint (point))
  1115.     nil
  1116.       (point))))
  1117.  
  1118.  
  1119. ;; Perhaps something could be done to handle VMS' own backups.
  1120.  
  1121. (defun dired-clean-directory (keep)
  1122.   "Flag numerical backups for deletion.
  1123. Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
  1124. Positive prefix arg KEEP overrides `dired-kept-versions';
  1125. Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
  1126.  
  1127. To clear the flags on these files, you can use \\[dired-flag-backup-files]
  1128. with a prefix argument."
  1129.   (interactive "P")
  1130.   (setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
  1131.   (let ((early-retention (if (< keep 0) (- keep) kept-old-versions))
  1132.     (late-retention (if (<= keep 0) dired-kept-versions keep))
  1133.     (file-version-assoc-list ()))
  1134.     (message "Cleaning numerical backups (keeping %d late, %d old)..."
  1135.          late-retention early-retention)
  1136.     ;; Look at each file.
  1137.     ;; If the file has numeric backup versions,
  1138.     ;; put on file-version-assoc-list an element of the form
  1139.     ;; (FILENAME . VERSION-NUMBER-LIST)
  1140.     (dired-map-dired-file-lines (function dired-collect-file-versions))
  1141.     ;; Sort each VERSION-NUMBER-LIST,
  1142.     ;; and remove the versions not to be deleted.
  1143.     (let ((fval file-version-assoc-list))
  1144.       (while fval
  1145.     (let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
  1146.            (v-count (length sorted-v-list)))
  1147.       (if (> v-count (+ early-retention late-retention))
  1148.           (rplacd (nthcdr early-retention sorted-v-list)
  1149.               (nthcdr (- v-count late-retention)
  1150.                   sorted-v-list)))
  1151.       (rplacd (car fval)
  1152.           (cdr sorted-v-list)))
  1153.     (setq fval (cdr fval))))
  1154.     ;; Look at each file.  If it is a numeric backup file,
  1155.     ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
  1156.     (dired-map-dired-file-lines (function dired-trample-file-versions))
  1157.     (message "Cleaning numerical backups...done")))
  1158.  
  1159. ;;; Subroutines of dired-clean-directory.
  1160.  
  1161. (defun dired-map-dired-file-lines (fun)
  1162.   ;; Perform FUN with point at the end of each non-directory line.
  1163.   ;; FUN takes one argument, the filename (complete pathname).
  1164.   (dired-check-ls-l)
  1165.   (save-excursion
  1166.     (let (file buffer-read-only)
  1167.       (goto-char (point-min))
  1168.       (while (not (eobp))
  1169.     (save-excursion
  1170.       (and (not (looking-at dired-re-dir))
  1171.            (not (eolp))
  1172.            (setq file (dired-get-filename nil t)) ; nil on non-file
  1173.            (progn (end-of-line)
  1174.               (funcall fun file))))
  1175.     (forward-line 1)))))
  1176.  
  1177. (defun dired-collect-file-versions (fn)
  1178.   ;;  "If it looks like file FN has versions, return a list of the versions.
  1179.   ;;That is a list of strings which are file names.
  1180.   ;;The caller may want to flag some of these files for deletion."
  1181.     (let* ((base-versions
  1182.         (concat (file-name-nondirectory fn) ".~"))
  1183.        (bv-length (length base-versions))
  1184.        (possibilities (file-name-all-completions
  1185.                base-versions
  1186.                (file-name-directory fn)))
  1187.        (versions (mapcar 'backup-extract-version possibilities)))
  1188.       (if versions
  1189.       (setq file-version-assoc-list (cons (cons fn versions)
  1190.                           file-version-assoc-list)))))
  1191.  
  1192. (defun dired-trample-file-versions (fn)
  1193.   (let* ((start-vn (string-match "\\.~[0-9]+~$" fn))
  1194.      base-version-list)
  1195.     (and start-vn
  1196.      (setq base-version-list    ; there was a base version to which
  1197.            (assoc (substring fn 0 start-vn)    ; this looks like a
  1198.               file-version-assoc-list))    ; subversion
  1199.      (not (memq (string-to-int (substring fn (+ 2 start-vn)))
  1200.             base-version-list))    ; this one doesn't make the cut
  1201.      (progn (beginning-of-line)
  1202.         (delete-char 1)
  1203.         (insert dired-del-marker)))))
  1204.  
  1205.  
  1206. ;; Keeping Dired buffers in sync with the filesystem and with each other
  1207.  
  1208. (defvar dired-buffers nil
  1209.   ;; Enlarged by dired-advertise
  1210.   ;; Queried by function dired-buffers-for-dir. When this detects a
  1211.   ;; killed buffer, it is removed from this list.
  1212.   "Alist of directories and their associated dired buffers.")
  1213.  
  1214. (defun dired-buffers-for-dir (dir)
  1215. ;; Return a list of buffers that dired DIR (top level or in-situ subdir).
  1216. ;; The list is in reverse order of buffer creation, most recent last.
  1217. ;; As a side effect, killed dired buffers for DIR are removed from
  1218. ;; dired-buffers.
  1219.   (setq dir (file-name-as-directory dir))
  1220.   (let ((alist dired-buffers) result elt)
  1221.     (while alist
  1222.       (setq elt (car alist))
  1223.       (if (dired-in-this-tree dir (car elt))
  1224.       (let ((buf (cdr elt)))
  1225.         (if (buffer-name buf)
  1226.         (if (assoc dir (save-excursion
  1227.                  (set-buffer buf)
  1228.                  dired-subdir-alist))
  1229.             (setq result (cons buf result)))
  1230.           ;; else buffer is killed - clean up:
  1231.           (setq dired-buffers (delq elt dired-buffers)))))
  1232.       (setq alist (cdr alist)))
  1233.     result))
  1234.  
  1235. (defun dired-advertise ()
  1236.   ;;"Advertise in variable `dired-buffers' that we dired `default-directory'."
  1237.   ;; With wildcards we actually advertise too much.
  1238.   (if (memq (current-buffer) (dired-buffers-for-dir default-directory))
  1239.       t                    ; we have already advertised ourselves
  1240.     (setq dired-buffers
  1241.       (cons (cons default-directory (current-buffer))
  1242.         dired-buffers))))
  1243.  
  1244. (defun dired-unadvertise (dir)
  1245.   ;; Remove DIR from the buffer alist in variable dired-buffers.
  1246.   ;; This has the effect of removing any buffer whose main directory is DIR.
  1247.   ;; It does not affect buffers in which DIR is a subdir.
  1248.   ;; Removing is also done as a side-effect in dired-buffer-for-dir.
  1249.   (setq dired-buffers
  1250.       (delq (assoc dir dired-buffers) dired-buffers)))
  1251.  
  1252. (defun dired-fun-in-all-buffers (directory fun &rest args)
  1253.   ;; In all buffers dired'ing DIRECTORY, run FUN with ARGS.
  1254.   ;; Return list of buffers where FUN succeeded (i.e., returned non-nil).
  1255.   (let ((buf-list (dired-buffers-for-dir directory))
  1256.     (obuf (current-buffer))
  1257.     buf success-list)
  1258.     (while buf-list
  1259.       (setq buf (car buf-list)
  1260.         buf-list (cdr buf-list))
  1261.       (unwind-protect
  1262.       (progn
  1263.         (set-buffer buf)
  1264.         (if (apply fun args)
  1265.         (setq success-list (cons (buffer-name buf) success-list))))
  1266.     (set-buffer obuf)))
  1267.     success-list))
  1268.  
  1269. (defun dired-add-file (filename &optional marker-char)
  1270.   (dired-fun-in-all-buffers
  1271.    (file-name-directory filename)
  1272.    (function dired-add-entry) filename marker-char))
  1273.  
  1274. (defun dired-add-entry (filename &optional marker-char)
  1275.   ;; Add a new entry for FILENAME, optionally marking it
  1276.   ;; with MARKER-CHAR (a character, else dired-marker-char is used).
  1277.   ;; Note that this adds the entry `out of order' if files sorted by
  1278.   ;; time, etc.
  1279.   ;; At least this version inserts in the right subdirectory (if present).
  1280.   ;; And it skips "." or ".." (see `dired-trivial-filenames').
  1281.   ;; Hidden subdirs are exposed if a file is added there.
  1282.   (setq filename (directory-file-name filename))
  1283.   ;; Entry is always for files, even if they happen to also be directories
  1284.   (let ((opoint (point))
  1285.     (cur-dir (dired-current-directory))
  1286.     (directory (file-name-directory filename))
  1287.     reason)
  1288.     (setq filename (file-name-nondirectory filename)
  1289.       reason
  1290.       (catch 'not-found
  1291.         (if (string= directory cur-dir)
  1292.         (progn
  1293.           (if (dired-subdir-hidden-p cur-dir)
  1294.               (dired-unhide-subdir))
  1295.           ;; We are already where we should be, except when
  1296.           ;; point is before the subdir line or its total line.
  1297.           (let ((p (dired-after-subdir-garbage cur-dir)))
  1298.             (if (< (point) p)
  1299.             (goto-char p))))
  1300.           ;; else try to find correct place to insert
  1301.           (if (dired-goto-subdir directory)
  1302.           (progn;; unhide if necessary
  1303.             (if (looking-at "\r");; point is at end of subdir line
  1304.             (dired-unhide-subdir))
  1305.             ;; found - skip subdir and `total' line
  1306.             ;; and uninteresting files like . and ..
  1307.             ;; This better not moves into the next subdir!
  1308.             (dired-goto-next-nontrivial-file))
  1309.         ;; not found
  1310.         (throw 'not-found "Subdir not found")))
  1311.         ;; found and point is at The Right Place:
  1312.         (let (buffer-read-only)
  1313.           (beginning-of-line)
  1314.           (dired-add-entry-do-indentation marker-char)
  1315.           (dired-ls (dired-make-absolute filename directory);; don't expand `.' !
  1316.             (concat dired-actual-switches "d"))
  1317.           (forward-line -1)
  1318.           ;; We want to have the non-directory part, only:
  1319.           (let* ((beg (dired-move-to-filename t)) ; error for strange output
  1320.              (end (dired-move-to-end-of-filename)))
  1321.         (setq filename (buffer-substring beg end))
  1322.         (delete-region beg end)
  1323.         (insert (file-name-nondirectory filename)))
  1324.           (if dired-after-readin-hook;; the subdir-alist is not affected...
  1325.           (save-excursion;; ...so we can run it right now:
  1326.             (save-restriction
  1327.               (beginning-of-line)
  1328.               (narrow-to-region (point) (save-excursion
  1329.                           (forward-line 1) (point)))
  1330.               (run-hooks 'dired-after-readin-hook))))
  1331.           (dired-move-to-filename))
  1332.         ;; return nil if all went well
  1333.         nil))
  1334.     (if reason                ; don't move away on failure
  1335.     (goto-char opoint))
  1336.     (not reason)))            ; return t on succes, nil else
  1337.  
  1338. ;; This is a separate function for the sake of nested dired format.
  1339. (defun dired-add-entry-do-indentation (marker-char)
  1340.   ;; two spaces or a marker plus a space:
  1341.   (insert (if marker-char
  1342.           (if (integerp marker-char) marker-char dired-marker-char)
  1343.         ?\040)
  1344.       ?\040))
  1345.  
  1346. (defun dired-after-subdir-garbage (dir)
  1347.   ;; Return pos of first file line of DIR, skipping header and total
  1348.   ;; or wildcard lines.
  1349.   ;; Important: never moves into the next subdir.
  1350.   ;; DIR is assumed to be unhidden.
  1351.   ;; Will probably be redefined for VMS etc.
  1352.   (save-excursion
  1353.     (or (dired-goto-subdir dir) (error "This cannot happen"))
  1354.     (forward-line 1)
  1355.     (while (and (not (eolp))        ; don't cross subdir boundary
  1356.         (not (dired-move-to-filename)))
  1357.     (forward-line 1))
  1358.     (point)))
  1359.  
  1360. (defun dired-remove-file (file)
  1361.   (dired-fun-in-all-buffers
  1362.    (file-name-directory file) (function dired-remove-entry) file))
  1363.  
  1364. (defun dired-remove-entry (file)
  1365.   (save-excursion
  1366.     (and (dired-goto-file file)
  1367.      (let (buffer-read-only)
  1368.        (delete-region (progn (beginning-of-line) (point))
  1369.               (save-excursion (forward-line 1) (point)))))))
  1370.  
  1371. (defun dired-relist-file (file)
  1372.   (dired-fun-in-all-buffers (file-name-directory file)
  1373.                 (function dired-relist-entry) file))
  1374.  
  1375. (defun dired-relist-entry (file)
  1376.   ;; Relist the line for FILE, or just add it if it did not exist.
  1377.   ;; FILE must be an absolute pathname.
  1378.   (let (buffer-read-only marker)
  1379.     ;; If cursor is already on FILE's line delete-region will cause
  1380.     ;; save-excursion to fail because of floating makers,
  1381.     ;; moving point to beginning of line.  Sigh.
  1382.     (save-excursion
  1383.       (and (dired-goto-file file)
  1384.        (delete-region (progn (beginning-of-line)
  1385.                  (setq marker (following-char))
  1386.                  (point))
  1387.               (save-excursion (forward-line 1) (point))))
  1388.       (setq file (directory-file-name file))
  1389.       (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
  1390.  
  1391. (defun dired-update-file-line (file)
  1392.   ;; Delete the current line, and insert an entry for FILE.
  1393.   ;; If FILE is nil, then just delete the current line.
  1394.   ;; Keeps any marks that may be present in column one (doing this
  1395.   ;; here is faster than with dired-add-entry's optional arg).
  1396.   ;; Does not update other dired buffers.  Use dired-relist-entry for that.
  1397.   (beginning-of-line)
  1398.   (let ((char (following-char)) (opoint (point)))
  1399.     (delete-region (point) (progn (forward-line 1) (point)))
  1400.     (if file
  1401.     (progn
  1402.       (dired-add-entry file)
  1403.       ;; Replace space by old marker without moving point.
  1404.       ;; Faster than goto+insdel inside a save-excursion?
  1405.       (subst-char-in-region opoint (1+ opoint) ?\040 char))))
  1406.   (dired-move-to-filename))
  1407.  
  1408.  
  1409. ;; Running subprocesses, checking and logging of their errors.
  1410.  
  1411. (defvar dired-log-buf "*Dired log*")
  1412.  
  1413. (defun dired-why ()
  1414.   "Pop up a buffer with error log output from Dired.
  1415. A group of errors from a single command ends with a formfeed.
  1416. Thus, use \\[backward-page] to find the beginning of a group of errors."
  1417.   (interactive)
  1418.   (let ((obuf (current-buffer)))
  1419.     (pop-to-buffer dired-log-buf)
  1420.     (goto-char (point-max))
  1421.     (recenter -1)
  1422.     (switch-to-buffer-other-window obuf)))
  1423.  
  1424. (defun dired-log (log &rest args)
  1425.   ;; Log a message or the contents of a buffer.
  1426.   ;; If LOG is a string and there are more args, it is formatted with
  1427.   ;; those ARGS.  Usually the LOG string ends with a \n.
  1428.   ;; End each bunch of errors with (dired-log t): this inserts
  1429.   ;; current time and buffer, and a \f (formfeed).
  1430.   (let ((obuf (current-buffer)))
  1431.     (unwind-protect            ; want to move point
  1432.     (progn
  1433.       (set-buffer (get-buffer-create dired-log-buf))
  1434.       (goto-char (point-max))
  1435.       (let (buffer-read-only)
  1436.         (cond ((stringp log)
  1437.            (insert (if args
  1438.                    (apply (function format) log args)
  1439.                  log)))
  1440.           ((bufferp log)
  1441.            (insert-buffer log))
  1442.           ((eq t log)
  1443.            (insert "\n\t" (current-time-string)
  1444.                "\tBuffer `" (buffer-name obuf) "'\n\f\n")))))
  1445.       (set-buffer obuf))))
  1446.  
  1447. (defun dired-log-summary (log &rest args)
  1448.   ;; Log a summary describing a bunch of errors.
  1449.   (apply (function dired-log) (concat "\n" log) args)
  1450.   (dired-log t))
  1451.  
  1452. ;; In Emacs 19 this will return program's exit status.
  1453. ;; This is a separate function so that ange-ftp can redefine it.
  1454. (defun dired-call-process (program discard &rest arguments)
  1455. ;  "Run PROGRAM with output to current buffer unless DISCARD is t.
  1456. ;Remaining arguments are strings passed as command arguments to PROGRAM."
  1457.   (apply 'call-process program nil (not discard) nil arguments))
  1458.  
  1459. (defun dired-check-process-checker (exit-status)
  1460.   ;; In Emacs 19, EXIT-STATUS comes from (dired-)call-process
  1461.   ;; Then this function should return (/= 0 exit-status)
  1462.   ;; In Emacs 18 the exit status is not accessible, so we
  1463.   ;; do the following which is not always correct as some compress
  1464.   ;; programs are verbose by default or otherwise braindamaged
  1465.   (if (and dired-emacs-19-p exit-status)
  1466.       (/= 0 exit-status);; #### install (does it work in Emacs 19?)
  1467.     (/= 0 (buffer-size)))        ; run in program's output buffer
  1468.   ;; If have you one of those compress programs, you might
  1469.   ;; want to redefine this function to look closer at compress' output.
  1470.   ;; This is why it is a separate function.
  1471.   )
  1472.  
  1473. (defun dired-check-process (msg program &rest arguments)
  1474. ;  "Display MSG while running PROGRAM, and check for output.
  1475. ;Remaining arguments are strings passed as command arguments to PROGRAM.
  1476. ; On error as determined by dired-check-process-checker, insert output
  1477. ; in a log buffer and return the offending ARGUMENTS or PROGRAM.
  1478. ; Caller can cons up a list of failed args.
  1479. ;Else returns nil for success."
  1480.   (let (err-buffer err (dir default-directory))
  1481.     (message "%s..." msg)
  1482.     (save-excursion
  1483.       ;; Get a clean buffer for error output:
  1484.       (setq err-buffer (get-buffer-create " *dired-check-process output*"))
  1485.       (set-buffer err-buffer)
  1486.       (erase-buffer)
  1487.       (setq default-directory dir    ; caller's default-directory
  1488.         err (dired-check-process-checker
  1489.          (apply (function dired-call-process) program nil arguments)))
  1490.       (if err
  1491.       (progn
  1492.         (dired-log (concat program " " (prin1-to-string arguments) "\n"))
  1493.         (dired-log err-buffer)
  1494.         (or arguments program t))
  1495.     (kill-buffer err-buffer)
  1496.     (message "%s...done" msg)
  1497.     nil))))
  1498.  
  1499. ;;; 7K
  1500. ;;;###begin dired-cmd.el
  1501. ;; Diffing and compressing
  1502.  
  1503. (defun dired-diff (file &optional switches)
  1504.   "Compare file at point with file FILE using `diff'.
  1505. FILE defaults to the file at the mark.
  1506. The prompted-for file is the first file given to `diff'.
  1507. Prefix arg lets you edit the diff switches.  See the command `diff'."
  1508.   (interactive
  1509.    (let ((default (if (mark)
  1510.               (save-excursion (goto-char (mark))
  1511.                       (dired-get-filename t t)))))
  1512.      (list (read-file-name (format "Diff %s with: %s"
  1513.                    (dired-get-filename t)
  1514.                    (if default
  1515.                        (concat "(default " default ") ")
  1516.                      ""))
  1517.                (dired-current-directory) default t)
  1518.        (if (fboundp 'diff-read-switches)
  1519.            (diff-read-switches "Options for diff: ")))))
  1520.   (if switches                ; Emacs 19's diff has but two
  1521.       (diff file (dired-get-filename t) switches) ; args (yet ;-)
  1522.     (diff file (dired-get-filename t))))
  1523.  
  1524. (defun dired-backup-diff (&optional switches)
  1525.   "Diff this file with its backup file or vice versa.
  1526. Uses the latest backup, if there are several numerical backups.
  1527. If this file is a backup, diff it with its original.
  1528. The backup file is the first file given to `diff'.
  1529. Prefix arg lets you edit the diff switches.  See the command `diff'."
  1530.   (interactive (list (if (fboundp 'diff-read-switches)
  1531.              (diff-read-switches "Diff with switches: "))))
  1532.   (let (bak ori (file (dired-get-filename)))
  1533.     (if (backup-file-name-p file)
  1534.     (setq bak file
  1535.           ori (file-name-sans-versions file))
  1536.       (setq bak (or (latest-backup-file file)
  1537.             (error "No backup found for %s" file))
  1538.         ori file))
  1539.     (if switches
  1540.     (diff bak ori switches)
  1541.       (diff bak ori))))
  1542.  
  1543. ;;#### install (move this function into files.el)
  1544. (defun latest-backup-file (fn)    ; actually belongs into files.el
  1545.   "Return the latest existing backup of FILE, or nil."
  1546.   ;; First try simple backup, then the highest numbered of the
  1547.   ;; numbered backups.
  1548.   ;; Ignore the value of version-control because we look for existing
  1549.   ;; backups, which maybe were made earlier or by another user with
  1550.   ;; a different value of version-control.
  1551.   (setq fn (expand-file-name fn))
  1552.   (or
  1553.    (let ((bak (make-backup-file-name fn)))
  1554.      (if (file-exists-p bak) bak))
  1555.    (let* ((dir (file-name-directory fn))
  1556.       (base-versions (concat (file-name-nondirectory fn) ".~"))
  1557.       (bv-length (length base-versions)))
  1558.      (concat dir
  1559.          (car (sort
  1560.            (file-name-all-completions base-versions dir)
  1561.            ;; bv-length is a fluid var for backup-extract-version:
  1562.            (function
  1563.             (lambda (fn1 fn2)
  1564.               (> (backup-extract-version fn1)
  1565.              (backup-extract-version fn2))))))))))
  1566.  
  1567. ;; This is a separate function for the sake of ange-ftp.el
  1568. (defun dired-compress-make-compressed-filename (from-file &optional reverse)
  1569. ;;  "Converts a filename FROM-FILE to the filename of the associated
  1570. ;;  compressed file.  With an optional argument REVERSE, the reverse
  1571. ;;  conversion is done."
  1572.  
  1573.   (if reverse
  1574.       
  1575.       ;; uncompress...
  1576.       ;; return `nil' if no match found -- better than nothing
  1577.       (let (case-fold-search ; case-sensitive search
  1578.             (string
  1579.              (concat "\\.\\(g?z\\|" (regexp-quote dired-gzip-file-extension)
  1580.                      "$\\|Z\\)$")))
  1581.  
  1582.         (and (string-match string from-file)
  1583.              (substring from-file 0 (match-beginning 0))))
  1584.  
  1585.     ;; compress...
  1586.     ;; note: it could be that `gz' is not the proper extension for gzip
  1587.     (concat from-file 
  1588.             (if dired-use-gzip-instead-of-compress
  1589.                 dired-gzip-file-extension ".Z"))))
  1590.  
  1591.  
  1592. (defun dired-compress ()
  1593.   ;; Compress current file.  Return nil for success, offending filename else.
  1594.   (dired-check-ls-l)
  1595.   (let* (buffer-read-only
  1596.      (from-file (dired-get-filename))
  1597.      (to-file (dired-compress-make-compressed-filename from-file)))
  1598.     (cond ((save-excursion (beginning-of-line)
  1599.                (looking-at dired-re-sym))
  1600.        (dired-log (concat "Attempt to compress a symbolic link:\n"
  1601.                   from-file))
  1602.        (dired-make-relative from-file))
  1603.           (
  1604.  
  1605.            (if dired-use-gzip-instead-of-compress
  1606.                ;; gzip (GNU zip)
  1607.                ;; use `-q' (quiet) switch for gzip in case GZIP environment
  1608.                ;; variable contains `--verbose' - lrd - Feb 18, 1993
  1609.                (dired-check-process (concat "Gzip'ing " from-file)
  1610.                                     "gzip" "--quiet" "--force" "--suffix"
  1611.                                     dired-gzip-file-extension from-file)
  1612.  
  1613.              (dired-check-process (concat "Compressing " from-file)
  1614.                                   "compress" "-f" from-file))
  1615.        ;; errors from the process are already logged by dired-check-process
  1616.        (dired-make-relative from-file))
  1617.     (t
  1618.      (dired-update-file-line to-file)
  1619.      nil))))
  1620.  
  1621. (defun dired-uncompress ()
  1622.   ;; Uncompress current file.  Return nil for success, offending filename else.
  1623.   (let* (buffer-read-only
  1624.      (from-file (dired-get-filename))
  1625.      (to-file (dired-compress-make-compressed-filename from-file t)))
  1626.     (if
  1627.         (if dired-use-gzip-instead-of-compress
  1628.             ;; gzip (GNU zip)
  1629.             ;; use `-q' (quiet) switch for gzip in case GZIP environment
  1630.             ;; variable contains `--verbose' - lrd - Feb 18, 1993
  1631.             (dired-check-process (concat "Gunzip'ing " from-file)
  1632.                                  "gzip" "--decompress" "--quiet" "--suffix"
  1633.                                  dired-gzip-file-extension from-file)
  1634.  
  1635.           (dired-check-process (concat "Uncompressing " from-file)
  1636.                                "uncompress" from-file))
  1637.  
  1638.     (dired-make-relative from-file)
  1639.       (dired-update-file-line to-file)
  1640.       nil)))
  1641.  
  1642. (defun dired-mark-map-check (fun arg op-symbol &optional show-progress)
  1643. ;  "Map FUN over marked files (with second ARG like in dired-mark-map)
  1644. ; and display failures.
  1645.  
  1646. ; FUN takes zero args.  It returns non-nil (the offending object, e.g.
  1647. ; the short form of the filename) for a failure and probably logs a
  1648. ; detailed error explanation using function `dired-log'.
  1649.  
  1650. ; OP-SYMBOL is a symbol describing the operation performed (e.g.
  1651. ; `compress').  It is used with `dired-mark-pop-up' to prompt the user
  1652. ; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
  1653. ; `Failed to compress 1 of 2 files - type W to see why ("foo")')
  1654.  
  1655. ; SHOW-PROGRESS if non-nil means redisplay dired after each file."
  1656.   (if (dired-mark-confirm op-symbol arg)
  1657.       (let* ((total-list;; all of FUN's return values
  1658.           (dired-mark-map (funcall fun) arg show-progress))
  1659.          (total (length total-list))
  1660.          (failures (delq nil total-list))
  1661.          (count (length failures)))
  1662.     (if (not failures)
  1663.         (message "%s: %d file%s."
  1664.              (capitalize (symbol-name op-symbol))
  1665.              total (dired-plural-s total))
  1666.       (message "Failed to %s %d of %d file%s - type W to see why %s"
  1667.            (symbol-name op-symbol) count total (dired-plural-s total)
  1668.            ;; this gives a short list of failed files in parens
  1669.            ;; which may be sufficient for the user even
  1670.            ;; without typing `W' for the process' diagnostics
  1671.            failures)
  1672.       ;; end this bunch of errors:
  1673.       (dired-log-summary
  1674.        "Failed to %s %d of %d file%s"
  1675.        (symbol-name op-symbol) count total (dired-plural-s total))))))
  1676.  
  1677. (defun dired-do-compress (&optional arg)
  1678.   "Compress marked (or next ARG) files.
  1679. Type \\[dired-do-uncompress] to uncompress again."
  1680.   (interactive "P")
  1681.   (dired-mark-map-check (function dired-compress) arg 'compress t))
  1682.  
  1683. (defun dired-do-uncompress (&optional arg)
  1684.   "Uncompress marked (or next ARG) files."
  1685.   (interactive "P")
  1686.   (dired-mark-map-check (function dired-uncompress) arg 'uncompress t))
  1687.  
  1688. ;; Commands for Emacs Lisp files - load and byte compile
  1689.  
  1690. (defun dired-byte-compile ()
  1691.   ;; Return nil for success, offending file name else.
  1692.   (let* ((filename (dired-get-filename))
  1693.      (elc-file
  1694.       (if (eq system-type 'vax-vms)
  1695.           (concat (substring filename 0 (string-match ";" filename)) "c")
  1696.         (concat filename "c")))
  1697.      buffer-read-only failure)
  1698.     (condition-case err
  1699.     (save-excursion (byte-compile-file filename))
  1700.       (error
  1701.        (setq failure err)))
  1702.     (if failure
  1703.     (progn
  1704.       (dired-log "Byte compile error for %s:\n%s\n" filename failure)
  1705.       (dired-make-relative filename))
  1706.       (dired-remove-file elc-file)
  1707.       (forward-line)            ; insert .elc after its .el file
  1708.       (dired-add-file elc-file)
  1709.       nil)))
  1710.  
  1711. (defun dired-do-byte-compile (&optional arg)
  1712.   "Byte compile marked (or next ARG) Emacs lisp files."
  1713.   (interactive "P")
  1714.   (dired-mark-map-check (function dired-byte-compile) arg 'byte-compile t))
  1715.  
  1716. (defun dired-load ()
  1717.   ;; Return nil for success, offending file name else.
  1718.   (let ((file (dired-get-filename)) failure)
  1719.     (condition-case err
  1720.       (load file nil nil t)
  1721.       (error (setq failure err)))
  1722.     (if (not failure)
  1723.     nil
  1724.       (dired-log "Load error for %s:\n%s\n" file failure)
  1725.       (dired-make-relative file))))
  1726.  
  1727. (defun dired-do-load (&optional arg)
  1728.   "Load the marked (or next ARG) Emacs lisp files."
  1729.   (interactive "P")
  1730.   (dired-mark-map-check (function dired-load) arg 'load t))
  1731.  
  1732. (defun dired-do-chxxx (attribute-name program op-symbol arg)
  1733.   ;; Change file attributes (mode, group, owner) of marked files and
  1734.   ;; refresh their file lines.
  1735.   ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
  1736.   ;; PROGRAM is the program used to change the attribute.
  1737.   ;; OP-SYMBOL is the type of operation (for use in dired-mark-pop-up).
  1738.   ;; ARG describes which files to use, like in dired-mark-get-files.
  1739.   (let* ((files (dired-mark-get-files t arg))
  1740.      (new-attribute
  1741.       (dired-mark-read-string
  1742.        (concat "Change " attribute-name " of %s to: ")
  1743.        nil op-symbol arg files))
  1744.      (operation (concat program " " new-attribute))
  1745.      (failure (apply (function dired-check-process)
  1746.              operation program new-attribute
  1747.              files)))
  1748.     (dired-do-redisplay arg);; moves point if ARG is an integer
  1749.     (if failure
  1750.     (dired-log-summary
  1751.      (message "%s: error - type W to see why." operation)))))
  1752.  
  1753. (defun dired-do-chmod (&optional arg)
  1754.   "Change the mode of the marked (or next ARG) files.
  1755. This calls chmod, thus symbolic modes like `g+w' are allowed."
  1756.   (interactive "P")
  1757.   (dired-do-chxxx "Mode" "chmod" 'chmod arg))
  1758.  
  1759. (defun dired-do-chgrp (&optional arg)
  1760.   "Change the group of the marked (or next ARG) files."
  1761.   (interactive "P")
  1762.   (dired-do-chxxx "Group" "chgrp" 'chgrp arg))
  1763.  
  1764. (defun dired-do-chown (&optional arg)
  1765.   "Change the owner of the marked (or next ARG) files."
  1766.   (interactive "P")
  1767.   (dired-do-chxxx "Owner" dired-chown-program 'chown arg))
  1768.  
  1769. ;;;###end dired-cmd.el
  1770.  
  1771.  
  1772. ;; Deleting files
  1773.  
  1774. (defun dired-do-deletions ()
  1775.   "In dired, delete the files flagged for deletion."
  1776.   (interactive)
  1777.   (let* ((dired-marker-char dired-del-marker)
  1778.      (regexp (dired-marker-regexp))
  1779.      case-fold-search)
  1780.     (if (save-excursion (goto-char (point-min))
  1781.             (re-search-forward regexp nil t))
  1782.     (dired-internal-do-deletions
  1783.      ;; this can't move point since ARG is nil
  1784.      (dired-mark-map (cons (dired-get-filename) (point))
  1785.              nil)
  1786.      nil)
  1787.       (message "(No deletions requested)"))))
  1788.  
  1789. (defun dired-do-delete (&optional arg)
  1790.   "Delete all marked (or next ARG) files."
  1791.   ;; This is more consistent with the file marking feature than
  1792.   ;; dired-do-deletions.
  1793.   (interactive "P")
  1794.   (dired-internal-do-deletions
  1795.    ;; this may move point if ARG is an integer
  1796.    (dired-mark-map (cons (dired-get-filename) (point))
  1797.            arg)
  1798.    arg))
  1799.  
  1800. (defvar dired-deletion-confirmer 'yes-or-no-p) ; or y-or-n-p?
  1801.  
  1802. (defun dired-internal-do-deletions (l arg)
  1803.   ;; L is an alist of files to delete, with their buffer positions.
  1804.   ;; ARG is the prefix arg.
  1805.   ;; Filenames are absolute (VMS needs this for logical search paths).
  1806.   ;; (car L) *must* be the *last* (bottommost) file in the dired buffer.
  1807.   ;; That way as changes are made in the buffer they do not shift the
  1808.   ;; lines still to be changed, so the (point) values in L stay valid.
  1809.   ;; Also, for subdirs in natural order, a subdir's files are deleted
  1810.   ;; before the subdir itself - the other way around would not work.
  1811.   (let ((files (mapcar (function car) l))
  1812.     (count (length l))
  1813.     (succ 0))
  1814.     ;; canonicalize file list for pop up
  1815.     (setq files (nreverse (mapcar (function dired-make-relative) files)))
  1816.     (if (dired-mark-pop-up
  1817.      " *Deletions*" 'delete files dired-deletion-confirmer
  1818.      (format "Delete %s " (dired-mark-prompt arg files)))
  1819.     (save-excursion
  1820.       (let (failures);; files better be in reverse order for this loop!
  1821.         (while l
  1822.           (goto-char (cdr (car l)))
  1823.           (let (buffer-read-only)
  1824.         (condition-case err
  1825.             (let ((fn (car (car l))))
  1826.               ;; This test is equivalent to
  1827.               ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1828.               ;; but more efficient
  1829.               (if (eq t (car (file-attributes fn)))
  1830.               (remove-directory fn)
  1831.             (delete-file fn))
  1832.               ;; if we get here, removing worked
  1833.               (setq succ (1+ succ))
  1834.               (message "%s of %s deletions" succ count)
  1835.               (delete-region (progn (beginning-of-line) (point))
  1836.                      (progn (forward-line 1) (point)))
  1837.               (dired-clean-up-after-deletion fn))
  1838.           (error;; catch errors from failed deletions
  1839.            (dired-log "%s\n" err)
  1840.            (setq failures (cons (car (car l)) failures)))))
  1841.           (setq l (cdr l)))
  1842.         (if (not failures)
  1843.         (message "%d deletion%s done" count (dired-plural-s count))
  1844.           (dired-log-summary
  1845.            (message "%d of %d deletion%s failed: %s"
  1846.             (length failures) count
  1847.             (dired-plural-s count)
  1848.             (prin1-to-string failures))))))
  1849.       (message "(No deletions performed)")))
  1850.   (dired-move-to-filename))
  1851.  
  1852. ;; This is a separate function for the sake of dired-x.el.
  1853. (defun dired-clean-up-after-deletion (fn)
  1854.   ;; Clean up after a deleted file or directory FN.
  1855.   (save-excursion (and (dired-goto-subdir fn)
  1856.                (dired-kill-subdir))))
  1857.  
  1858.  
  1859. (defun dired-replace-in-string (regexp newtext string)
  1860.   ;; Replace REGEXP with NEWTEXT everywhere in STRING and return result.
  1861.   ;; NEWTEXT is taken literally---no \\DIGIT escapes will be recognized.
  1862.   (let ((result "") (start 0) mb me)
  1863.     (while (string-match regexp string start)
  1864.       (setq mb (match-beginning 0)
  1865.         me (match-end 0)
  1866.         result (concat result (substring string start mb) newtext)
  1867.         start me))
  1868.     (concat result (substring string start))))
  1869.  
  1870. (defun dired-next-dirline (arg &optional opoint)
  1871.   "Goto ARG'th next directory file line."
  1872.   (interactive "_p")
  1873.   (dired-check-ls-l)
  1874.   (or opoint (setq opoint (point)))
  1875.   (if (if (> arg 0)
  1876.       (re-search-forward dired-re-dir nil t arg)
  1877.     (beginning-of-line)
  1878.     (re-search-backward dired-re-dir nil t (- arg)))
  1879.       (dired-move-to-filename)        ; user may type `i' or `f'
  1880.     (goto-char opoint)
  1881.     (error "No more subdirectories")))
  1882.  
  1883. (defun dired-prev-dirline (arg)
  1884.   "Goto ARG'th previous directory file line."
  1885.   (interactive "_p")
  1886.   (dired-next-dirline (- arg)))
  1887.  
  1888. (defun dired-unflag-all-files (flag &optional arg)
  1889.   "Remove a specific or all flags from every file.
  1890. With an arg, queries for each marked file.
  1891. Type \\[help-command] at that time for help."
  1892.   (interactive "sRemove flag: (default: all flags) \nP")
  1893.   (let ((count 0)
  1894.     (re (if (zerop (length flag)) dired-re-mark
  1895.           (concat "^" (regexp-quote flag)))))
  1896.     (save-excursion
  1897.       (let (buffer-read-only case-fold-search query
  1898.                  (help-form "\
  1899. Type SPC or `y' to unflag one file, DEL or `n' to skip to next,
  1900. `!' to unflag all remaining files with no more questions."))
  1901.     (goto-char (point-min))
  1902.     (while (re-search-forward re nil t)
  1903.       (if (or (not arg)
  1904.           (dired-query 'query "Unflag file `%s' ? "
  1905.                    (dired-get-filename t)))
  1906.           (progn (delete-char -1) (insert " ") (setq count (1+ count))))
  1907.       (forward-line 1))))
  1908.     (message "%s" (format "Flags removed: %d %s" count flag) )))
  1909.  
  1910. ;; pop ups and user input for file marking
  1911.  
  1912. (defun dired-marker-regexp ()
  1913.   (concat "^" (regexp-quote (char-to-string dired-marker-char))))
  1914.  
  1915. (defun dired-plural-s (count)
  1916.   (if (= 1 count) "" "s"))
  1917.  
  1918. (defun dired-mark-prompt (arg files)
  1919.   ;; Return a string for use in a prompt, either the current file
  1920.   ;; name, or the marker and a count of marked files.
  1921.   (let ((count (length files)))
  1922.     (if (= count 1)
  1923.     (car files)
  1924.       ;; more than 1 file:
  1925.       (if (integerp arg)
  1926.       ;; abs(arg) = count
  1927.       ;; Perhaps this is nicer, but it also takes more screen space:
  1928.       ;;(format "[%s %d files]" (if (> arg 0) "next" "previous")
  1929.       ;;                        count)
  1930.       (format "[next %d files]" arg)
  1931.     (format "%c [%d files]" dired-marker-char count)))))
  1932.  
  1933. (defvar dired-query-alist
  1934.   '((?\y . y) (?\040 . y)        ; `y' or SPC means accept once
  1935.     (?n . n) (?\177 . n)        ; `n' or DEL skips once
  1936.     (?! . yes)                ; `!' accepts rest
  1937.     (?q. no) (?\e . no)            ; `q' or ESC skips rest
  1938.     ;; None of these keys quit - use C-g for that.
  1939.     ))
  1940.  
  1941. (defun dired-query (qs-var qs-prompt &rest qs-args)
  1942.   ;; Query user and return nil or t.
  1943.   ;; Store answer in symbol VAR (which must initially be bound to nil).
  1944.   ;; Format PROMPT with ARGS.
  1945.   ;; Binding variable help-form will help the user who types C-h.
  1946.   (let* ((char (symbol-value qs-var))
  1947.      (action (cdr (assoc char dired-query-alist))))
  1948.     (cond ((eq 'yes action)
  1949.        t)                ; accept, and don't ask again
  1950.       ((eq 'no action)
  1951.        nil)                ; skip, and don't ask again
  1952.       (t;; no lasting effects from last time we asked - ask now
  1953.        (let ((qprompt (concat qs-prompt
  1954.                   (if help-form
  1955.                       (format " [Type yn!q or %s] "
  1956.                           (key-description
  1957.                            (char-to-string help-char)))
  1958.                     " [Type y, n, q or !] ")))
  1959.          result elt)
  1960.          ;; Actually it looks nicer without cursor-in-echo-area - you can
  1961.          ;; look at the dired buffer instead of at the prompt to decide.
  1962.          (apply 'message qprompt qs-args)
  1963.          (setq char (set qs-var (read-char)))
  1964.          (while (not (setq elt (assoc char dired-query-alist)))
  1965.            (message "Invalid char - type %c for help." help-char)
  1966.            (ding)
  1967.            (sit-for 1)
  1968.            (apply 'message qprompt qs-args)
  1969.            (setq char (set qs-var (read-char))))
  1970.          (memq (cdr elt) '(t y yes)))))))
  1971.  
  1972. (defun dired-pop-to-buffer (buf)
  1973.   ;; Pop up buffer BUF.
  1974.   ;; If dired-shrink-to-fit is t, make its window fit its contents.
  1975.   (if (not dired-shrink-to-fit)
  1976.       (pop-to-buffer (get-buffer-create buf))
  1977.     ;; let window shrink to fit:
  1978.     (let ((window (selected-window))
  1979.       target-lines w2)
  1980.       (cond ;; if split-window-threshold is enabled, use the largest window
  1981.             ((and (> (window-height (setq w2 (get-largest-window)))
  1982.              split-height-threshold)
  1983.           (= (screen-width) (window-width w2)))
  1984.          (setq window w2))
  1985.         ;; if the least-recently-used window is big enough, use it
  1986.         ((and (> (window-height (setq w2 (get-lru-window)))
  1987.              (* 2 window-min-height))
  1988.           (= (screen-width) (window-width w2)))
  1989.          (setq window w2)))
  1990.       (save-excursion
  1991.     (set-buffer buf)
  1992.     (goto-char (point-max))
  1993.     (skip-chars-backward "\n\r\t ")
  1994.     (setq target-lines (count-lines (point-min) (point))))
  1995.       (if (<= (window-height window) (* 2 window-min-height))
  1996.       ;; At this point, every window on the screen is too small to split.
  1997.       (setq w2 (display-buffer buf))
  1998.     (setq w2 (split-window window
  1999.           (max window-min-height
  2000.                (- (window-height window)
  2001.               (1+ (max window-min-height target-lines)))))))
  2002.       (set-window-buffer w2 buf)
  2003.       (if (< (1- (window-height w2)) target-lines)
  2004.       (progn
  2005.         (select-window w2)
  2006.         (enlarge-window (- target-lines (1- (window-height w2))))))
  2007.       (set-window-start w2 1)
  2008.       )))
  2009.  
  2010. (defvar dired-no-confirm nil
  2011. ;;  "If non-nil, list of symbols for commands dired should not confirm.
  2012. ;;It can be a sublist of
  2013. ;;
  2014. ;;  '(byte-compile chgrp chmod chown compress copy delete hardlink load
  2015. ;;    move print shell symlink uncompress)"
  2016.   )
  2017.  
  2018. (defun dired-mark-confirm (op-symbol arg)
  2019.   ;; Request confirmation from the user that the operation described
  2020.   ;; by OP-SYMBOL is to be performed on the marked files.
  2021.   ;; Confirmation consists in a y-or-n question with a file list
  2022.   ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
  2023.   ;; The files used are determined by ARG (like in dired-mark-get-files).
  2024.   (or (memq op-symbol dired-no-confirm)
  2025.       (let ((files (dired-mark-get-files t arg)))
  2026.     (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
  2027.                (concat (capitalize (symbol-name op-symbol)) " "
  2028.                    (dired-mark-prompt arg files) "? ")))))
  2029.  
  2030. (defun dired-mark-pop-up (bufname op-symbol files function &rest args)
  2031.   ;;"Args BUFNAME OP-SYMBOL FILES FUNCTION &rest ARGS.
  2032.   ;;Return FUNCTION's result on ARGS after popping up a window (in a buffer
  2033.   ;;named BUFNAME, nil gives \" *Marked Files*\") showing the marked
  2034.   ;;files.  Uses function `dired-pop-to-buffer' to do that.
  2035.   ;; FUNCTION should not manipulate files.
  2036.   ;; It should only read input (an argument or confirmation).
  2037.   ;;The window is not shown if there is just one file or
  2038.   ;; OP-SYMBOL is a member of the list in `dired-no-confirm'.
  2039.   ;;FILES is the list of marked files."
  2040.   (or bufname (setq bufname  " *Marked Files*"))
  2041.   (if (or (memq op-symbol dired-no-confirm)
  2042.       (= (length files) 1))
  2043.       (apply function args)
  2044.     (save-excursion
  2045.       (set-buffer (get-buffer-create bufname))
  2046.       (erase-buffer)
  2047.       (dired-format-columns-of-files files))
  2048.     (save-window-excursion
  2049.       (dired-pop-to-buffer bufname)
  2050.       (apply function args))))
  2051.  
  2052. (defun dired-format-columns-of-files (files)
  2053.   ;; Files should be in forward order for this loop.
  2054.   ;; i.e., (car files) = first file in buffer.
  2055.   ;; Returns the number of lines used.
  2056.   (let* ((maxlen (+ 2 (apply 'max (mapcar 'length files))))
  2057.      (width (- (window-width (selected-window)) 2))
  2058.      (columns (max 1 (/ width maxlen)))
  2059.      (nfiles (length files))
  2060.      (rows (+ (/ nfiles columns)
  2061.           (if (zerop (% nfiles columns)) 0 1)))
  2062.      (i 0)
  2063.      (j 0))
  2064.     (setq files (nconc (copy-sequence files) ; fill up with empty fns
  2065.                (make-list (- (* columns rows) nfiles) "")))
  2066.     (setcdr (nthcdr (1- (length files)) files) files) ; make circular
  2067.     (while (< j rows)
  2068.       (while (< i columns)
  2069.     (indent-to (* i maxlen))
  2070.     (insert (car files))
  2071.     (setq files (nthcdr rows files)
  2072.           i (1+ i)))
  2073.       (insert "\n")
  2074.       (setq i 0
  2075.         j (1+ j)
  2076.         files (cdr files)))
  2077.     rows))
  2078.  
  2079. ;; Read arguments for a mark command of type OP-SYMBOL,
  2080. ;; perhaps popping up the list of marked files.
  2081. ;; ARG is the prefix arg and indicates whether the files came from
  2082. ;; marks (ARG=nil) or a repeat factor (integerp ARG).
  2083. ;; If the current file was used, the list has but one element and ARG
  2084. ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
  2085.  
  2086. (defun dired-mark-read-string (prompt initial op-symbol arg files)
  2087.   ;; PROMPT for a string, with INITIAL input.
  2088.   ;; Other args are used to give user feedback and pop-up:
  2089.   ;; OP-SYMBOL of command, prefix ARG, marked FILES.
  2090.   (dired-mark-pop-up
  2091.    nil op-symbol files
  2092.    (function read-string)
  2093.    (format prompt (dired-mark-prompt arg files)) initial))
  2094.  
  2095. (defun dired-mark-read-file-name (prompt dir op-symbol arg files)
  2096.   (dired-mark-pop-up
  2097.    nil op-symbol files
  2098.    (function read-file-name)
  2099.    (format prompt (dired-mark-prompt arg files)) dir))
  2100.  
  2101. (defun dired-mark-file (arg)
  2102.   "In dired, mark the current line's file for later commands.
  2103. With arg, repeat over several lines.
  2104. Use \\[dired-unflag-all-files] to remove all flags."
  2105.   (interactive "p")
  2106.   (let (buffer-read-only)
  2107.     (dired-repeat-over-lines
  2108.      arg
  2109.      (function (lambda () (delete-char 1) (insert dired-marker-char))))))
  2110.  
  2111. (defun dired-next-marked-file (arg &optional wrap opoint)
  2112.   "Move to the next marked file, wrapping around the end of the buffer."
  2113.   (interactive "_p\np")
  2114.   (or opoint (setq opoint (point)));; return to where interactively started
  2115.   (if (if (> arg 0)
  2116.       (re-search-forward dired-re-mark nil t arg)
  2117.     (beginning-of-line)
  2118.     (re-search-backward dired-re-mark nil t (- arg)))
  2119.       (dired-move-to-filename)
  2120.     (if (null wrap)
  2121.     (progn
  2122.       (goto-char opoint)
  2123.       (error "No next marked file"))
  2124.       (message "(Wraparound for next marked file)")
  2125.       (goto-char (if (> arg 0) (point-min) (point-max)))
  2126.       (dired-next-marked-file arg nil opoint))))
  2127.  
  2128. (defun dired-prev-marked-file (arg &optional wrap)
  2129.   "Move to the previous marked file, wrapping around the end of the buffer."
  2130.   (interactive "_p\np")
  2131.   (dired-next-marked-file (- arg) wrap))
  2132.  
  2133. (defun dired-file-marker (file)
  2134.   ;; Return FILE's marker, or nil if unmarked.
  2135.   (save-excursion
  2136.     (and (dired-goto-file file)
  2137.      (progn
  2138.        (beginning-of-line)
  2139.        (if (not (equal ?\040 (following-char)))
  2140.            (following-char))))))
  2141.  
  2142. (defun dired-read-regexp (prompt &optional initial)
  2143. ;; This is an extra function so that gmhist can redefine it.
  2144.   (setq dired-flagging-regexp
  2145.     (read-string prompt (or initial dired-flagging-regexp))))
  2146.  
  2147. (defun dired-mark-files-regexp (regexp &optional marker-char)
  2148.   "Mark all files matching REGEXP for use in later commands.
  2149. A prefix argument means to unmark them instead.
  2150. `.' and `..' are never marked.
  2151.  
  2152. REGEXP is an Emacs regexp, not a shell wildcard.  Thus, use `\\.o$' for
  2153. object files--just `.o' will mark more than you might think."
  2154.   (interactive
  2155.    (list (dired-read-regexp (concat (if current-prefix-arg "Unmark" "Mark")
  2156.                     " files (regexp): "))
  2157.      (if current-prefix-arg ?\040)))
  2158.   (let ((dired-marker-char (or marker-char dired-marker-char)))
  2159.     (dired-mark-if
  2160.      (and (not (looking-at dired-re-dot))
  2161.       (not (eolp))            ; empty line
  2162.       (let ((fn (dired-get-filename nil t)))
  2163.         (and fn (string-match regexp (file-name-nondirectory fn)))))
  2164.      "matching file")))
  2165.  
  2166. (defun dired-flag-regexp-files (regexp)
  2167.   "In dired, flag all files containing the specified REGEXP for deletion.
  2168. The match is against the non-directory part of the filename.  Use `^'
  2169.   and `$' to anchor matches.  Exclude subdirs by hiding them.
  2170. `.' and `..' are never flagged."
  2171.   (interactive (list (dired-read-regexp "Flag for deletion (regexp): ")))
  2172.   (dired-mark-files-regexp regexp dired-del-marker))
  2173.  
  2174. (defun dired-mark-symlinks (unflag-p)
  2175.   "Mark all symbolic links.
  2176. With prefix argument, unflag all those files."
  2177.   (interactive "P")
  2178.   (dired-check-ls-l)
  2179.   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  2180.     (dired-mark-if (looking-at dired-re-sym) "symbolic link")))
  2181.  
  2182. (defun dired-mark-directories (unflag-p)
  2183.   "Mark all directory file lines except `.' and `..'.
  2184. With prefix argument, unflag all those files."
  2185.   (interactive "P")
  2186.   (dired-check-ls-l)
  2187.   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  2188.     (dired-mark-if (and (looking-at dired-re-dir)
  2189.             (not (looking-at dired-re-dot)))
  2190.            "directory file")))
  2191.  
  2192. (defun dired-mark-executables (unflag-p)
  2193.   "Mark all executable files.
  2194. With prefix argument, unflag all those files."
  2195.   (interactive "P")
  2196.   (dired-check-ls-l)
  2197.   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  2198.     (dired-mark-if (looking-at dired-re-exe) "executable file")))
  2199.  
  2200. ;; dired-x.el has a dired-mark-sexp interactive command: mark
  2201. ;; files for which PREDICATE returns non-nil.
  2202.  
  2203. (defun dired-flag-auto-save-files (&optional unflag-p)
  2204.   "Flag for deletion files whose names suggest they are auto save files.
  2205. A prefix argument says to unflag those files instead."
  2206.   (interactive "P")
  2207.   (dired-check-ls-l)
  2208.   (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
  2209.     (dired-mark-if
  2210.        (and (not (looking-at dired-re-dir))
  2211.         (let ((fn (dired-get-filename t t)))
  2212.           (if fn (auto-save-file-name-p
  2213.               (file-name-nondirectory fn)))))
  2214.        "auto save file")))
  2215.  
  2216. (defun dired-flag-backup-files (&optional unflag-p)
  2217.   "Flag all backup files (names ending with `~') for deletion.
  2218. With prefix argument, unflag these files."
  2219.   (interactive "P")
  2220.   (dired-check-ls-l)
  2221.   (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
  2222.     (dired-mark-if
  2223.      (and (not (looking-at dired-re-dir))
  2224.       (let ((fn (dired-get-filename t t)))
  2225.         (if fn (backup-file-name-p fn))))
  2226.      "backup file")))
  2227.  
  2228.  
  2229. ;;; Shell commands
  2230. ;;#### install (move this function into simple.el)
  2231. (defun shell-quote (filename)        ; actually belongs into simple.el
  2232.   "Quote a file name for inferior shell (see variable shell-file-name)."
  2233.   ;; Quote everything except POSIX filename characters.
  2234.   ;; This should be safe enough even for really wierd shells.
  2235.   (let ((result "") (start 0) end)
  2236.     (while (string-match "[^---0-9a-zA-Z_./]" filename start)
  2237.       (setq end (match-beginning 0)
  2238.         result (concat result (substring filename start end)
  2239.                "\\" (substring filename end (1+ end)))
  2240.         start (1+ end)))
  2241.     (concat result (substring filename start))))
  2242.  
  2243. (defun dired-read-shell-command (prompt arg files)
  2244. ;;  "Read a dired shell command prompting with PROMPT (using read-string).
  2245. ;;ARG is the prefix arg and may be used to indicate in the prompt which
  2246. ;;  files are affected.
  2247. ;;This is an extra function so that you can redefine it, e.g., to use gmhist."
  2248.   (dired-mark-pop-up
  2249.    nil 'shell files
  2250.    (function read-string) (format prompt (dired-mark-prompt arg files))))
  2251.  
  2252. ;; The in-background argument is only needed in Emacs 18 where
  2253. ;; shell-command doesn't understand an appended ampersand `&'.
  2254. (defun dired-do-shell-command (&optional arg in-background)
  2255.   "Run a shell command on the marked files.
  2256. If there is output, it goes to a separate buffer.
  2257. The list of marked files is appended to the command string unless asterisks
  2258.   `*' indicate the place(s) where the list should go.
  2259. If no files are marked or a specific numeric prefix arg is given, uses
  2260.   next ARG files.  As always, a raw arg (\\[universal-argument]) means the current file.
  2261.   The prompt mentions the file(s) or the marker, as appropriate.
  2262. With a zero argument, run command on each marked file separately: `cmd *
  2263.   foo' results in `cmd F1 foo; ...; cmd Fn foo'.
  2264. No automatic redisplay is attempted, as the file names may have
  2265.   changed.  Type \\[dired-do-redisplay] to redisplay the marked files.
  2266. The shell command has the top level directory as working directory, so
  2267.   output files usually are created there instead of in a subdir."
  2268. ;;Functions dired-run-shell-command and dired-shell-stuff-it do the
  2269. ;;actual work and can be redefined for customization.
  2270.   (interactive "P")
  2271.   (let* ((on-each (equal arg 0))
  2272.      (prompt (concat (if in-background "& on " "! on ")
  2273.              (if on-each "each " "")
  2274.              "%s: "))
  2275.      (file-list (dired-mark-get-files t (if on-each nil arg)))
  2276.      ;; Want to give feedback whether this file or marked files are used:
  2277.      (command (dired-read-shell-command
  2278.            prompt (if on-each nil arg) file-list))
  2279.      (result
  2280.       (dired-shell-stuff-it command file-list on-each arg)))
  2281.     ;; execute the shell command
  2282.     (dired-run-shell-command result in-background)))
  2283.  
  2284. ;; Might use {,} for bash or csh:
  2285. (defvar dired-mark-prefix ""
  2286.   "Prepended to marked files in dired shell commands.")
  2287. (defvar dired-mark-postfix ""
  2288.   "Appended to marked files in dired shell commands.")
  2289. (defvar dired-mark-separator " "
  2290.   "Separates marked files in dired shell commands.")
  2291.  
  2292. (defun dired-shell-stuff-it (command file-list on-each &optional raw-arg)
  2293. ;; "Make up a shell command line from COMMAND and FILE-LIST.
  2294. ;; If ON-EACH is t, COMMAND should be applied to each file, else
  2295. ;; simply concat all files and apply COMMAND to this.
  2296. ;; FILE-LIST's elements will be quoted for the shell."
  2297. ;; Might be redefined for smarter things and could then use RAW-ARG
  2298. ;; (coming from interactive P and currently ignored) to decide what to do.
  2299. ;; Smart would be a way to access basename or extension of file names.
  2300. ;; See dired-trns.el for an approach to this.
  2301.   ;; Bug: There is no way to quote a *
  2302.   ;; On the other hand, you can never accidentally get a * into your cmd.
  2303.   (let ((stuff-it
  2304.      (if (string-match "\\*" command)
  2305.          (function (lambda (x)
  2306.              (dired-replace-in-string "\\*" x command)))
  2307.        (function (lambda (x) (concat command " " x))))))
  2308.     (if on-each
  2309.     (mapconcat stuff-it (mapcar (function shell-quote) file-list) ";")
  2310.       (let ((fns (mapconcat (function shell-quote)
  2311.                 file-list dired-mark-separator)))
  2312.     (if (> (length file-list) 1)
  2313.         (setq fns (concat dired-mark-prefix fns dired-mark-postfix)))
  2314.     (funcall stuff-it fns)))))
  2315.  
  2316. ;; This is an extra function so that it can be redefined by ange-ftp.
  2317. (defun dired-run-shell-command (command &optional in-background)
  2318.   (if (and in-background (not (string-match "&[ \t]*$" command)))
  2319.       (setq command (concat command " &")))
  2320.   (shell-command command))
  2321.  
  2322. (defun dired-do-print (&optional arg)
  2323.   "Print the marked (or next ARG) files.
  2324. Uses the shell command coming from variables `lpr-command' and
  2325. `lpr-switches' as default."
  2326.   (interactive "P")
  2327.   (or (listp lpr-switches)
  2328.       (error "lpr-switches must be a *list* of strings"))
  2329.   (let* ((file-list (dired-mark-get-files t arg))
  2330.      (switches (mapconcat (function identity) lpr-switches " "))
  2331.      (command (dired-mark-read-string
  2332.            "Print %s with: "
  2333.            (concat lpr-command " " switches)
  2334.            'print arg file-list)))
  2335.     (dired-run-shell-command (dired-shell-stuff-it command file-list nil))))
  2336.  
  2337.  
  2338. ;;; 10K
  2339. ;;;###begin dired-cp.el
  2340. ;;; Copy, move/rename, making hard and symbolic links
  2341.  
  2342. (defvar dired-backup-if-overwrite nil
  2343.   "*Non-nil if Dired should ask about making backups before overwriting files.
  2344. Special value 'always suppresses confirmation.")
  2345.  
  2346. (defun dired-handle-overwrite (to)
  2347.   ;; Save old version of a to be overwritten file TO.
  2348.   ;; `overwrite-confirmed' and `overwrite-backup-query' are fluid vars
  2349.   ;; from dired-create-files.
  2350.   (if (and dired-backup-if-overwrite
  2351.        overwrite-confirmed
  2352.        (or (eq 'always dired-backup-if-overwrite)
  2353.            (dired-query 'overwrite-backup-query
  2354.             (format "Make backup for existing file `%s'? " to))))
  2355.       (let ((backup (car (find-backup-file-name to))))
  2356.     (rename-file to backup 0)    ; confirm overwrite of old backup
  2357.     (dired-relist-entry backup))))
  2358.  
  2359. (defun dired-copy-file (from to ok-flag)
  2360.   (dired-handle-overwrite to)
  2361.   (copy-file from to ok-flag dired-copy-preserve-time))
  2362.  
  2363. (defun dired-rename-file (from to ok-flag)
  2364.   (dired-handle-overwrite to)
  2365.   (rename-file from to ok-flag)        ; error is caught in -create-files
  2366.   ;; Silently rename the visited file of any buffer visiting this file.
  2367.   (and (get-file-buffer from)
  2368.        (save-excursion
  2369.      (set-buffer (get-file-buffer from))
  2370.      (let ((modflag (buffer-modified-p)))
  2371.        (set-visited-file-name to)    ; kills write-file-hooks
  2372.        (set-buffer-modified-p modflag))))
  2373.   (dired-remove-file from)
  2374.   ;; See if it's an inserted subdir, and rename that, too.
  2375.   (dired-rename-subdir from to))
  2376.  
  2377. (defun dired-rename-subdir (from-dir to-dir)
  2378.   (setq from-dir (file-name-as-directory from-dir)
  2379.     to-dir (file-name-as-directory to-dir))
  2380.   (dired-fun-in-all-buffers from-dir
  2381.                 (function dired-rename-subdir-1) from-dir to-dir)
  2382.   ;; Update visited file name of all affected buffers
  2383.   (let ((blist (buffer-list)))
  2384.     (while blist
  2385.       (save-excursion
  2386.         (set-buffer (car blist))
  2387.     (if (and buffer-file-name
  2388.          (dired-in-this-tree buffer-file-name from-dir))
  2389.         (let ((modflag (buffer-modified-p))
  2390.           (to-file (dired-replace-in-string
  2391.                 (concat "^" (regexp-quote from-dir))
  2392.                 to-dir
  2393.                 buffer-file-name)))
  2394.           (set-visited-file-name to-file)
  2395.           (set-buffer-modified-p modflag))))
  2396.       (setq blist (cdr blist)))))
  2397.  
  2398. (defun dired-rename-subdir-1 (dir to)
  2399.   ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
  2400.   ;; one of its subdirectories is expanded in this buffer.
  2401.   (let ((alist dired-subdir-alist)
  2402.     (elt nil))
  2403.     (while alist
  2404.       (setq elt (car alist)
  2405.         alist (cdr alist))
  2406.       (if (dired-in-this-tree (car elt) dir)
  2407.       ;; ELT's subdir is affected by the rename
  2408.       (dired-rename-subdir-2 elt dir to)))
  2409.     (if (equal dir default-directory)
  2410.     ;; if top level directory was renamed, lots of things have to be
  2411.     ;; updated:
  2412.     (progn
  2413.       (dired-unadvertise dir)    ; we no longer dired DIR...
  2414.       (setq default-directory to
  2415.         dired-directory (expand-file-name;; this is correct
  2416.                  ;; with and without wildcards
  2417.                  (file-name-nondirectory dired-directory)
  2418.                  to))
  2419.       (let ((new-name (file-name-nondirectory
  2420.                (directory-file-name dired-directory))))
  2421.         ;; try to rename buffer, but just leave old name if new
  2422.         ;; name would already exist (don't try appending "<%d>")
  2423.         (or (get-buffer new-name)
  2424.         (rename-buffer new-name)))
  2425.       ;; ... we dired TO now:
  2426.       (dired-advertise)))))
  2427.  
  2428. (defun dired-rename-subdir-2 (elt dir to)
  2429.   ;; Update the headerline and dired-subdir-alist element of directory
  2430.   ;; described by alist-element ELT to reflect the moving of DIR to TO.
  2431.   ;; Thus, ELT describes either DIR itself or a subdir of DIR.
  2432.  
  2433.   ;; Bug: If TO is not longer part of the same dired tree as DIR was,
  2434.   ;; updating the headerline is actually not the right thing---it
  2435.   ;; should be removed in that case and a completely new entry be
  2436.   ;; added for TO.  Actually, removing and adding anew would always be
  2437.   ;; the right (but slow) way of doing it.
  2438.  
  2439.   ;; The consequences are pretty harmless though (no updates since
  2440.   ;; dired-buffers-for-dir will not suspect it to be in this dired
  2441.   ;; buffer).
  2442.  
  2443.   (save-excursion
  2444.     (let ((regexp (regexp-quote (directory-file-name dir)))
  2445.       (newtext (directory-file-name to))
  2446.       buffer-read-only)
  2447.       (goto-char (dired-get-subdir-min elt))
  2448.       ;; Update subdir headerline in buffer
  2449.       (if (not (looking-at dired-subdir-regexp))
  2450.       (error "%s not found where expected - dired-subdir-alist broken?"
  2451.          dir)
  2452.     (goto-char (match-beginning 1))
  2453.     (if (re-search-forward regexp (match-end 1) t)
  2454.         (replace-match newtext t t)
  2455.       (error "Expected to find `%s' in headerline of %s" dir (car elt))))
  2456.       ;; Update buffer-local dired-subdir-alist
  2457.       (setcar elt
  2458.           (dired-normalize-subdir
  2459.            (dired-replace-in-string regexp newtext (car elt)))))))
  2460.  
  2461. ;; Cloning replace-match to work on strings instead of in buffer:
  2462. ;; The FIXEDCASE parameter of replace-match is not implemented.
  2463. (defun dired-string-replace-match (regexp string newtext
  2464.                       &optional literal global)
  2465.   "Replace first match of REGEXP in STRING with NEWTEXT.
  2466. If it does not match, nil is returned instead of the new string.
  2467. Optional arg LITERAL means to take NEWTEXT literally.
  2468. Optional arg GLOBAL means to replace all matches."
  2469.   (if global
  2470.         (let ((result "") (start 0) mb me)
  2471.       (while (string-match regexp string start)
  2472.         (setq mb (match-beginning 0)
  2473.           me (match-end 0)
  2474.           result (concat result
  2475.                  (substring string start mb)
  2476.                  (if literal
  2477.                      newtext
  2478.                    (dired-expand-newtext string newtext)))
  2479.           start me))
  2480.       (if mb            ; matched at least once
  2481.           (concat result (substring string start))
  2482.         nil))
  2483.     ;; not GLOBAL
  2484.     (if (not (string-match regexp string 0))
  2485.     nil
  2486.       (concat (substring string 0 (match-beginning 0))
  2487.           (if literal newtext (dired-expand-newtext string newtext))
  2488.           (substring string (match-end 0))))))
  2489.  
  2490. (defun dired-expand-newtext (string newtext)
  2491.   ;; Expand \& and \1..\9 (referring to STRING) in NEWTEXT, using match data.
  2492.   ;; Note that in Emacs 18 match data are clipped to current buffer
  2493.   ;; size...so the buffer should better not be smaller than STRING.
  2494.   (let ((pos 0)
  2495.     (len (length newtext))
  2496.     (expanded-newtext ""))
  2497.     (while (< pos len)
  2498.       (setq expanded-newtext
  2499.         (concat expanded-newtext
  2500.             (let ((c (aref newtext pos)))
  2501.               (if (= ?\\ c)
  2502.               (cond ((= ?\& (setq c
  2503.                           (aref newtext
  2504.                             (setq pos (1+ pos)))))
  2505.                  (substring string
  2506.                         (match-beginning 0)
  2507.                         (match-end 0)))
  2508.                 ((and (>= c ?1) (<= c ?9))
  2509.                  ;; return empty string if N'th
  2510.                  ;; sub-regexp did not match:
  2511.                  (let ((n (- c ?0)))
  2512.                    (if (match-beginning n)
  2513.                        (substring string
  2514.                           (match-beginning n)
  2515.                           (match-end n))
  2516.                      "")))
  2517.                 (t
  2518.                  (char-to-string c)))
  2519.             (char-to-string c)))))
  2520.       (setq pos (1+ pos)))
  2521.     expanded-newtext))
  2522.  
  2523. ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
  2524. (defun dired-create-files (file-creator operation fn-list name-constructor
  2525.                     &optional marker-char)
  2526.  
  2527. ;; Create a new file for each from a list of existing files.  The user
  2528. ;; is queried, dired buffers are updated, and at the end a success or
  2529. ;; failure message is displayed
  2530.  
  2531. ;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists
  2532.  
  2533. ;; It is called for each file and must create newfile, the entry of
  2534. ;; which will be added.  The user will be queried if the file already
  2535. ;; exists.  If oldfile is removed by FILE-CREATOR (i.e, it is a
  2536. ;; rename), it is FILE-CREATOR's responsibility to update dired
  2537. ;; buffers.  FILE-CREATOR must abort by signalling a file-error if it
  2538. ;; could not create newfile.  The error is caught and logged.
  2539.  
  2540. ;; OPERATION (a capitalized string, e.g. `Copy') describes the
  2541. ;; operation performed.  It is used for error logging.
  2542.  
  2543. ;; FN-LIST is the list of files to copy (full absolute pathnames).
  2544.  
  2545. ;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to
  2546. ;; skip.  If it skips files for other reasons than a direct user
  2547. ;; query, it is supposed to tell why (using dired-log).
  2548.  
  2549. ;; Optional MARKER-CHAR is a character with which to mark every
  2550. ;; newfile's entry, or t to use the current marker character if the
  2551. ;; oldfile was marked.
  2552.  
  2553.   (let (failures skipped (success-count 0) (total (length fn-list)))
  2554.     (let (to overwrite-query
  2555.          overwrite-backup-query)    ; for dired-handle-overwrite
  2556.       (mapcar
  2557.        (function
  2558.     (lambda (from)
  2559.       (setq to (funcall name-constructor from))
  2560.       (if (equal to from)
  2561.           (progn
  2562.         (setq to nil)
  2563.         (dired-log "Cannot %s to same file: %s\n"
  2564.                (downcase operation) from)))
  2565.       (if (not to)
  2566.           (setq skipped (cons (dired-make-relative from) skipped))
  2567.         (let* ((overwrite (file-exists-p to))
  2568.            (overwrite-confirmed    ; for dired-handle-overwrite
  2569.             (and overwrite
  2570.              (let ((help-form '(format "\
  2571. Type SPC or `y' to overwrite file `%s',
  2572. DEL or `n' to skip to next,
  2573. ESC or `q' to not overwrite any of the remaining files,
  2574. `!' to overwrite all remaining files with no more questions." to)))
  2575.                (dired-query 'overwrite-query
  2576.                     "Overwrite `%s'?" to))))
  2577.            ;; must determine if FROM is marked before file-creator
  2578.            ;; gets a chance to delete it (in case of a move).
  2579.            (actual-marker-char
  2580.             (cond  ((integerp marker-char) marker-char)
  2581.                (marker-char (dired-file-marker from)) ; slow
  2582.                (t nil))))
  2583.           (condition-case err
  2584.           (progn
  2585.             (funcall file-creator from to overwrite-confirmed)
  2586.             (if overwrite
  2587.             ;; If we get here, file-creator hasn't been aborted
  2588.             ;; and the old entry (if any) has to be deleted
  2589.             ;; before adding the new entry.
  2590.             (dired-remove-file to))
  2591.             (setq success-count (1+ success-count))
  2592.             (message "%s: %d of %d" operation success-count total)
  2593.             (dired-add-file to actual-marker-char))
  2594.         (file-error        ; FILE-CREATOR aborted
  2595.          (progn
  2596.            (setq failures (cons (dired-make-relative from) failures))
  2597.            (dired-log "%s `%s' to `%s' failed:\n%s\n"
  2598.                   operation from to err))))))))
  2599.        fn-list))
  2600.     (cond
  2601.      (failures
  2602.       (dired-log-summary
  2603.        (message "%s failed for %d of %d file%s %s"
  2604.         operation (length failures) total
  2605.         (dired-plural-s total) failures)))
  2606.      (skipped
  2607.       (dired-log-summary
  2608.        (message "%s: %d of %d file%s skipped %s"
  2609.         operation (length skipped) total
  2610.         (dired-plural-s total) skipped)))
  2611.      (t
  2612.       (message "%s: %s file%s."
  2613.            operation success-count (dired-plural-s success-count)))))
  2614.   (dired-move-to-filename))
  2615.  
  2616. (defun dired-do-create-files (op-symbol file-creator operation arg
  2617.                          &optional marker-char op1
  2618.                          how-to)
  2619.   ;; Create a new file for each marked file.
  2620.   ;; Prompts user for target, which is a directory in which to create
  2621.   ;;   the new files.  Target may be a plain file if only one marked
  2622.   ;;   file exists.
  2623.   ;; OP-SYMBOL is the symbol for the operation.  Function `dired-mark-pop-up'
  2624.   ;;   will determine wether pop-ups are appropriate for this OP-SYMBOL.
  2625.   ;; FILE-CREATOR and OPERATION as in dired-create-files.
  2626.   ;; ARG as in dired-mark-get-files.
  2627.   ;; Optional arg OP1 is an alternate form for OPERATION if there is
  2628.   ;;   only one file.
  2629.   ;; Optional arg MARKER-CHAR as in dired-create-files.
  2630.   ;; Optional arg HOW-TO determines how to treat target:
  2631.   ;;   If HOW-TO is not given (or nil), and target is a directory, the
  2632.   ;;     file(s) are created inside the target directory.  If target
  2633.   ;;     is not a directory, there must be exactly one marked file,
  2634.   ;;     else error.
  2635.   ;;   If HOW-TO is t, then target is not modified.  There must be
  2636.   ;;     exactly one marked file, else error.
  2637.   ;; Else HOW-TO is assumed to be a function of one argument, target,
  2638.   ;;     that looks at target and returns a value for the into-dir
  2639.   ;;     variable.  The function dired-into-dir-with-symlinks is provided
  2640.   ;;     for the case (common when creating symlinks) that symbolic
  2641.   ;;     links to directories are not to be considered as directories
  2642.   ;;     (as file-directory-p would if HOW-TO had been nil).
  2643.   (or op1 (setq op1 operation))
  2644.   (let* ((fn-list (dired-mark-get-files nil arg))
  2645.      (fn-count (length fn-list))
  2646.      (target (expand-file-name
  2647.            (dired-mark-read-file-name
  2648.             (concat (if (= 1 fn-count) op1 operation) " %s to: ")
  2649.             (dired-dwim-target-directory)
  2650.             op-symbol arg (mapcar (function dired-make-relative) fn-list))))
  2651.      (into-dir (cond ((null how-to) (file-directory-p target))
  2652.              ((eq how-to t) nil)
  2653.              (t (funcall how-to target)))))
  2654.     (if (and (> fn-count 1)
  2655.          (not into-dir))
  2656.     (error "Marked %s: target must be a directory: %s" operation target))
  2657.     ;; rename-file bombs when moving directories unless we do this:
  2658.     (or into-dir (setq target (directory-file-name target)))
  2659.     (dired-create-files
  2660.      file-creator operation fn-list
  2661.      (if into-dir            ; target is a directory
  2662.      ;; This function uses fluid vars into-dir and target when called
  2663.      ;; inside dired-create-files:
  2664.      (function (lambda (from)
  2665.              (expand-file-name (file-name-nondirectory from) target)))
  2666.        (function (lambda (from) target)))
  2667.      marker-char)))
  2668.  
  2669. (defun dired-dwim-target-directory ()
  2670.   ;; Try to guess which target directory the user may want.
  2671.   ;; If there is a dired buffer displayed in the next window, use
  2672.   ;; its current subdir, else use current subdir of this dired buffer.
  2673.   (let ((this-dir (and (eq major-mode 'dired-mode)
  2674.                (dired-current-directory))))
  2675.     ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
  2676.     (if dired-dwim-target
  2677.     (let* ((other-buf (window-buffer (next-window)))
  2678.            (other-dir (save-excursion
  2679.                 (set-buffer other-buf)
  2680.                 (and (eq major-mode 'dired-mode)
  2681.                  (dired-current-directory)))))
  2682.       (or other-dir this-dir))
  2683.       this-dir)))
  2684.  
  2685. (defun dired-into-dir-with-symlinks (target)
  2686.   (and (file-directory-p target)
  2687.        (not (file-symlink-p target))))
  2688. ;; This may not always be what you want, especially if target is your
  2689. ;; home directory and it happens to be a symbolic link, as is often the
  2690. ;; case with NFS and automounters.  Or if you want to make symlinks
  2691. ;; into directories that themselves are only symlinks, also quite
  2692. ;; common.
  2693.  
  2694. ;; So we don't use this function as value for HOW-TO in
  2695. ;; dired-do-symlink, which has the minor disadvantage of
  2696. ;; making links *into* a symlinked-dir, when you really wanted to
  2697. ;; *overwrite* that symlink.  In that (rare, I guess) case, you'll
  2698. ;; just have to remove that symlink by hand before making your marked
  2699. ;; symlinks.
  2700.  
  2701. (defun dired-do-copy (&optional arg)
  2702.   "Copy all marked (or next ARG) files, or copy the current file.
  2703. Thus, a zero prefix argument copies nothing.  But it toggles the
  2704. variable `dired-copy-preserve-time' (which see)."
  2705.   (interactive "P")
  2706.   (if (not (zerop (prefix-numeric-value arg)))
  2707.       (dired-do-create-files 'copy (function dired-copy-file)
  2708.                    (if dired-copy-preserve-time "Copy [-p]" "Copy")
  2709.                    arg dired-keep-marker-copy)
  2710.     (setq dired-copy-preserve-time (not dired-copy-preserve-time))
  2711.     (if dired-copy-preserve-time
  2712.     (message "Copy will preserve time.")
  2713.       (message "Copied files will get current date."))))
  2714.  
  2715. (defun dired-do-symlink (&optional arg)
  2716.    "Symlink all marked (or next ARG) files into a directory,
  2717. or make a symbolic link to the current file."
  2718.   (interactive "P")
  2719.   (dired-do-create-files 'symlink (function make-symbolic-link)
  2720.                "SymLink" arg dired-keep-marker-symlink))
  2721.  
  2722. (defun dired-do-hardlink (&optional arg)
  2723.    "Hard-link all marked (or next ARG) files into a directory,
  2724. or make a hard link to the current file."
  2725.   (interactive "P")
  2726.   (dired-do-create-files 'hardlink (function add-name-to-file)
  2727.                "HardLink" arg dired-keep-marker-hardlink))
  2728.  
  2729. (defun dired-do-move (&optional arg)
  2730.   "Move all marked (or next ARG) files into a directory,
  2731. or rename the current file.
  2732. A zero ARG moves no files but toggles `dired-dwim-target' (which see)."
  2733.   (interactive "P")
  2734.   (if (not (zerop (prefix-numeric-value arg)))
  2735.       (dired-do-create-files 'move (function dired-rename-file)
  2736.                    "Move" arg dired-keep-marker-move "Rename")
  2737.     (setq dired-dwim-target (not dired-dwim-target))
  2738.     (message "dired-dwim-target is %s." (if dired-dwim-target "ON" "OFF"))))
  2739.  
  2740. ;;;###end dired-cp.el
  2741.  
  2742. ;;; 5K
  2743. ;;;###begin dired-re.el
  2744. (defun dired-do-create-files-regexp
  2745.   (file-creator operation arg regexp newname &optional whole-path marker-char)
  2746.   ;; Create a new file for each marked file using regexps.
  2747.   ;; FILE-CREATOR and OPERATION as in dired-create-files.
  2748.   ;; ARG as in dired-mark-get-files.
  2749.   ;; Matches each marked file against REGEXP and constructs the new
  2750.   ;;   filename from NEWNAME (like in function replace-match).
  2751.   ;; Optional arg WHOLE-PATH means match/replace the whole pathname
  2752.   ;;   instead of only the non-directory part of the file.
  2753.   ;; Optional arg MARKER-CHAR as in dired-create-files.
  2754.   (let* ((fn-list (dired-mark-get-files nil arg))
  2755.      (fn-count (length fn-list))
  2756.      (operation-prompt (concat operation " `%s' to `%s'?"))
  2757.      (rename-regexp-help-form (format "\
  2758. Type SPC or `y' to %s one match, DEL or `n' to skip to next,
  2759. `!' to %s all remaining matches with no more questions."
  2760.                       (downcase operation)
  2761.                       (downcase operation)))
  2762.      (regexp-name-constructor
  2763.       ;; Function to construct new filename using REGEXP and NEWNAME:
  2764.       (if whole-path        ; easy (but rare) case
  2765.           (function
  2766.            (lambda (from)
  2767.          (let ((to (dired-string-replace-match regexp from newname))
  2768.                ;; must bind help-form directly around call to
  2769.                ;; dired-query
  2770.                (help-form rename-regexp-help-form))
  2771.            (if to
  2772.                (and (dired-query 'rename-regexp-query
  2773.                      operation-prompt
  2774.                      from
  2775.                      to)
  2776.                 to)
  2777.              (dired-log "%s: %s did not match regexp %s\n"
  2778.                 operation from regexp)))))
  2779.         ;; not whole-path, replace non-directory part only
  2780.         (function
  2781.          (lambda (from)
  2782.            (let* ((new (dired-string-replace-match
  2783.                 regexp (file-name-nondirectory from) newname))
  2784.               (to (and new    ; nil means there was no match
  2785.                    (expand-file-name new
  2786.                          (file-name-directory from))))
  2787.               (help-form rename-regexp-help-form))
  2788.          (if to
  2789.              (and (dired-query 'rename-regexp-query
  2790.                        operation-prompt
  2791.                        (dired-make-relative from)
  2792.                        (dired-make-relative to))
  2793.               to)
  2794.            (dired-log "%s: %s did not match regexp %s\n"
  2795.                   operation (file-name-nondirectory from) regexp)))))))
  2796.      rename-regexp-query)
  2797.     (dired-create-files
  2798.      file-creator operation fn-list regexp-name-constructor marker-char)))
  2799.  
  2800. (defun dired-mark-read-regexp (operation)
  2801.   ;; Prompt user about performing OPERATION.
  2802.   ;; Read and return list of: regexp newname arg whole-path.
  2803.   (let* ((whole-path
  2804.       (equal 0 (prefix-numeric-value current-prefix-arg)))
  2805.      (arg
  2806.       (if whole-path nil current-prefix-arg))
  2807.      (regexp
  2808.       (dired-read-regexp
  2809.        (concat (if whole-path "Path " "") operation " from (regexp): ")
  2810.        dired-flagging-regexp))
  2811.      (newname
  2812.       (read-string
  2813.        (concat (if whole-path "Path " "") operation " " regexp " to: "))))
  2814.     (list regexp newname arg whole-path)))
  2815.  
  2816. (defun dired-do-rename-regexp (regexp newname &optional arg whole-path)
  2817.   "Rename marked files containing REGEXP to NEWNAME.
  2818. As each match is found, the user must type a character saying
  2819.   what to do with it.  For directions, type \\[help-command] at that time.
  2820. NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
  2821. REGEXP defaults to the last regexp used.
  2822. With a zero prefix arg, renaming by regexp affects the complete
  2823.   pathname - usually only the non-directory part of file names is used
  2824.   and changed."
  2825.   (interactive (dired-mark-read-regexp "Rename"))
  2826.   (dired-do-create-files-regexp
  2827.    (function dired-rename-file)
  2828.    "Rename" arg regexp newname whole-path dired-keep-marker-move))
  2829.  
  2830. (defun dired-do-copy-regexp (regexp newname &optional arg whole-path)
  2831.   "Copy all marked files containing REGEXP to NEWNAME.
  2832. See function `dired-rename-regexp' for more info."
  2833.   (interactive (dired-mark-read-regexp "Copy"))
  2834.   (dired-do-create-files-regexp
  2835.    (function dired-copy-file)
  2836.    (if dired-copy-preserve-time "Copy [-p]" "Copy")
  2837.    arg regexp newname whole-path dired-keep-marker-copy))
  2838.  
  2839. (defun dired-do-hardlink-regexp (regexp newname &optional arg whole-path)
  2840.   "Hardlink all marked files containing REGEXP to NEWNAME.
  2841. See function `dired-rename-regexp' for more info."
  2842.   (interactive (dired-mark-read-regexp "HardLink"))
  2843.   (dired-do-create-files-regexp
  2844.    (function add-name-to-file)
  2845.    "HardLink" arg regexp newname whole-path dired-keep-marker-hardlink))
  2846.  
  2847. (defun dired-do-symlink-regexp (regexp newname &optional arg whole-path)
  2848.   "Symlink all marked files containing REGEXP to NEWNAME.
  2849. See function `dired-rename-regexp' for more info."
  2850.   (interactive (dired-mark-read-regexp "SymLink"))
  2851.   (dired-do-create-files-regexp
  2852.    (function make-symbolic-link)
  2853.    "SymLink" arg regexp newname whole-path dired-keep-marker-symlink))
  2854.  
  2855. (defun dired-create-files-non-directory
  2856.   (file-creator basename-constructor operation arg)
  2857.   ;; Perform FILE-CREATOR on the non-directory part of marked files
  2858.   ;; using function BASENAME-CONSTRUCTOR, with query for each file.
  2859.   ;; OPERATION like in dired-create-files, ARG like in dired-mark-get-files.
  2860.   (let (rename-non-directory-query)
  2861.     (dired-create-files
  2862.      file-creator
  2863.      operation
  2864.      (dired-mark-get-files nil arg)
  2865.      (function
  2866.       (lambda (from)
  2867.     (let ((to (concat (file-name-directory from)
  2868.               (funcall basename-constructor
  2869.                    (file-name-nondirectory from)))))
  2870.       (and (let ((help-form (format "\
  2871. Type SPC or `y' to %s one file, DEL or `n' to skip to next,
  2872. `!' to %s all remaining matches with no more questions."
  2873.                     (downcase operation)
  2874.                     (downcase operation))))
  2875.          (dired-query 'rename-non-directory-query
  2876.                   (concat operation " `%s' to `%s'")
  2877.                   (dired-make-relative from)
  2878.                   (dired-make-relative to)))
  2879.            to))))
  2880.      dired-keep-marker-move)))
  2881.  
  2882. (defun dired-rename-non-directory (basename-constructor operation arg)
  2883.   (dired-create-files-non-directory
  2884.    (function dired-rename-file)
  2885.    basename-constructor operation arg))
  2886.  
  2887. (defun dired-upcase (&optional arg)
  2888.   "Rename all marked (or next ARG) files to upper case."
  2889.   (interactive "P")
  2890.   (dired-rename-non-directory (function upcase) "Rename upcase" arg))
  2891.  
  2892. (defun dired-downcase (&optional arg)
  2893.   "Rename all marked (or next ARG) files to lower case."
  2894.   (interactive "P")
  2895.   (dired-rename-non-directory (function downcase) "Rename downcase" arg))
  2896.  
  2897. ;;;###end dired-re.el
  2898.  
  2899.  
  2900. ;; Tree Dired
  2901.  
  2902. ;;; utility functions
  2903.  
  2904. (defun dired-in-this-tree (file dir)
  2905.   ;;"Is FILE part of the directory tree starting at DIR?"
  2906.   (let (case-fold-search)
  2907.     (string-match (concat "^" (regexp-quote dir)) file)))
  2908.  
  2909. (defun dired-make-absolute (file &optional dir)
  2910.   ;;"Convert FILE (a pathname relative to DIR) to an absolute pathname."
  2911.   ;; We can't always use expand-file-name as this would get rid of `.'
  2912.   ;; or expand in / instead default-directory if DIR=="".
  2913.   ;; This should be good enough for ange-ftp, but might easily be
  2914.   ;; redefined (for VMS?).
  2915.   ;; It should be reasonably fast, though, as it is called in
  2916.   ;; dired-get-filename.
  2917.   (concat (or dir default-directory) file))
  2918.  
  2919. (defun dired-make-relative (file &optional dir no-error)
  2920.   ;;"Convert FILE (an absolute pathname) to a pathname relative to DIR.
  2921.   ;; Else error (unless NO-ERROR is non-nil, then FILE is returned unchanged)
  2922.   ;;DIR defaults to default-directory."
  2923.   ;; DIR must be file-name-as-directory, as with all directory args in
  2924.   ;; elisp code.
  2925.   (or dir (setq dir default-directory))
  2926.   (if (string-match (concat "^" (regexp-quote dir)) file)
  2927.       (substring file (match-end 0))
  2928.     (if no-error
  2929.     file
  2930.       (error  "%s: not in directory tree growing at %s" file dir))))
  2931.  
  2932. (defun dired-normalize-subdir (dir)
  2933.   ;; Prepend default-directory to DIR if relative path name.
  2934.   ;; dired-get-filename must be able to make a valid filename from a
  2935.   ;; file and its directory DIR.
  2936.   (file-name-as-directory
  2937.    (if (file-name-absolute-p dir)
  2938.        dir
  2939.      (expand-file-name dir default-directory))))
  2940.  
  2941. (defun dired-between-files ()
  2942.   ;; Point must be at beginning of line
  2943.   ;; Should be equivalent to (save-excursion (not (dired-move-to-filename)))
  2944.   ;; but is about 1.5..2.0 times as fast. (Actually that's not worth it)
  2945.   (or (looking-at "^$\\|^. *$\\|^. total\\|^. wildcard")
  2946.       (looking-at dired-subdir-regexp)))
  2947.  
  2948. (defun dired-get-subdir ()
  2949.   ;;"Return the subdir name on this line, or nil if not on a headerline."
  2950.   ;; Look up in the alist whether this is a headerline.
  2951.   (save-excursion
  2952.     (let ((cur-dir (dired-current-directory)))
  2953.       (beginning-of-line)        ; alist stores b-o-l positions
  2954.       (and (zerop (- (point)
  2955.              (dired-get-subdir-min (assoc cur-dir
  2956.                           dired-subdir-alist))))
  2957.        cur-dir))))
  2958.  
  2959. ;(defun dired-get-subdir-min (elt)
  2960. ;  (cdr elt))
  2961. ;; can't use macro,  must be redefinable for other alist format in dired-nstd.
  2962. (fset 'dired-get-subdir-min 'cdr)
  2963.  
  2964. (defun dired-get-subdir-max (elt)
  2965.   (save-excursion
  2966.     (goto-char (dired-get-subdir-min elt))
  2967.     (dired-subdir-max)))
  2968.  
  2969. (defun dired-clear-alist ()
  2970.   (while dired-subdir-alist
  2971.     (set-marker (dired-get-subdir-min (car dired-subdir-alist)) nil)
  2972.     (setq dired-subdir-alist (cdr dired-subdir-alist))))
  2973.  
  2974. (defun dired-simple-subdir-alist ()
  2975.   ;; Build and return `dired-subdir-alist' assuming just the top level
  2976.   ;; directory to be inserted.  Don't parse the buffer.
  2977.   (set (make-local-variable 'dired-subdir-alist)
  2978.        (list (cons default-directory (point-min-marker)))))
  2979.  
  2980. (defun dired-build-subdir-alist ()
  2981.   "Build `dired-subdir-alist' by parsing the buffer and return it's new value."
  2982.   (interactive)
  2983.   (dired-clear-alist)
  2984.   (save-excursion
  2985.     (let ((count 0))
  2986.       (goto-char (point-min))
  2987.       (setq dired-subdir-alist nil)
  2988.       (while (re-search-forward dired-subdir-regexp nil t)
  2989.     (setq count (1+ count))
  2990.     (dired-alist-add-1 (buffer-substring (match-beginning 1)
  2991.                          (match-end 1))
  2992.              ;; Put subdir boundary between lines:
  2993.              (save-excursion
  2994.                (goto-char (match-beginning 0))
  2995.                (beginning-of-line)
  2996.                (point-marker)))
  2997.     (message "%d" count))
  2998.       (message "%d director%s." count (if (= 1 count) "y" "ies"))
  2999.       ;; We don't need to sort it because it is in buffer order per
  3000.       ;; constructionem.  Return new alist:
  3001.       dired-subdir-alist)))
  3002.  
  3003. (defun dired-alist-add (dir new-marker)
  3004.   ;; Add new DIR at NEW-MARKER.  Sort alist.
  3005.   (dired-alist-add-1 dir new-marker)
  3006.   (dired-alist-sort))
  3007.  
  3008. (defun dired-alist-add-1 (dir new-marker)
  3009.   ;; Add new DIR at NEW-MARKER.  Don't sort.
  3010.   (setq dired-subdir-alist
  3011.     (cons (cons (dired-normalize-subdir dir) new-marker)
  3012.           dired-subdir-alist)))
  3013.  
  3014. (defun dired-alist-sort ()
  3015.   ;; Keep the alist sorted on buffer position.
  3016.   (setq dired-subdir-alist
  3017.     (sort dired-subdir-alist
  3018.           (function (lambda (elt1 elt2)
  3019.               (> (dired-get-subdir-min elt1)
  3020.                  (dired-get-subdir-min elt2)))))))
  3021.  
  3022. (defun dired-unsubdir (dir)
  3023.   ;; Remove DIR from the alist
  3024.   (setq dired-subdir-alist
  3025.     (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
  3026.  
  3027. (defun dired-goto-next-nontrivial-file ()
  3028.   ;; Position point on first nontrivial file after point.
  3029.   (dired-goto-next-file);; so there is a file to compare with
  3030.   (if (stringp dired-trivial-filenames)
  3031.       (while (and (not (eobp))
  3032.           (string-match dired-trivial-filenames
  3033.                 (file-name-nondirectory
  3034.                  (or (dired-get-filename nil t) ""))))
  3035.     (forward-line 1)
  3036.     (dired-move-to-filename))))
  3037.  
  3038. (defun dired-goto-next-file ()
  3039.   (let ((max (1- (dired-subdir-max))))
  3040.     (while (and (not (dired-move-to-filename)) (< (point) max))
  3041.       (forward-line 1))))
  3042.  
  3043. (defun dired-goto-subdir (dir)
  3044.   "Goto end of header line of DIR in this dired buffer.
  3045. Return value of point on success, otherwise return nil.
  3046. The next char is either \\n, or \\r if DIR is hidden."
  3047.   (interactive
  3048.    (prog1                ; let push-mark display its message
  3049.        (list (expand-file-name
  3050.           (completing-read "Goto in situ directory: " ; prompt
  3051.                    dired-subdir-alist ; table
  3052.                    nil    ; predicate
  3053.                    t    ; require-match
  3054.                    (dired-current-directory))))
  3055.      (push-mark)))
  3056.   (setq dir (file-name-as-directory dir))
  3057.   (let ((elt (assoc dir dired-subdir-alist)))
  3058.     (and elt
  3059.      (goto-char (dired-get-subdir-min elt))
  3060.      ;; dired-subdir-hidden-p and dired-add-entry depend on point being
  3061.      ;; at either \r or \n after this function succeeds.
  3062.      (progn (skip-chars-forward "^\r\n")
  3063.         (point)))))
  3064.  
  3065. (defun dired-goto-file (file)
  3066.   "Goto file line of FILE in this dired buffer."
  3067.   ;; Return value of point on success, else nil.
  3068.   ;; FILE must be an absolute pathname.
  3069.   ;; Loses if FILE contains control chars like "\007" for which ls
  3070.   ;; either inserts "?" or "\\007" into the buffer, so we won't find
  3071.   ;; it in the buffer.
  3072.   (interactive
  3073.    (prog1                ; let push-mark display its message
  3074.        (list (expand-file-name
  3075.           (read-file-name "Goto file: "
  3076.                   (dired-current-directory))))
  3077.      (push-mark)))
  3078.   (setq file (directory-file-name file)) ; does no harm if no directory
  3079.   (let (found case-fold-search)
  3080.     (save-excursion
  3081.       (if (dired-goto-subdir (or (file-name-directory file)
  3082.                  (error "Need absolute pathname for %s" file)))
  3083.       (let ((base (file-name-nondirectory file))
  3084.         (boundary (dired-subdir-max)))
  3085.         (while (and (not found)
  3086.             ;; filenames are preceded by SPC, this makes
  3087.             ;; the search faster (e.g. for the filename "-"!).
  3088.             (search-forward (concat " " base) boundary 'move))
  3089.           ;; Match could have BASE just as initial substring or
  3090.           ;; or in permission bits or date or
  3091.           ;; not be a proper filename at all:
  3092.           (if (equal base (dired-get-filename 'no-dir t))
  3093.             ;; Must move to filename since an (actually
  3094.             ;; correct) match could have been elsewhere on the
  3095.             ;; ;; line (e.g. "-" would match somewhere in the
  3096.             ;; permission bits).
  3097.           (setq found (dired-move-to-filename)))))))
  3098.     (and found
  3099.      ;; return value of point (i.e., FOUND):
  3100.      (goto-char found))))
  3101.  
  3102. (defun dired-initial-position (dirname)
  3103.   ;; Where point should go in a new listing of DIRNAME.
  3104.   ;; Point assumed at beginning of new subdir line.
  3105.   ;; You may redefine this function as you wish, e.g. like in dired-x.el.
  3106.   (end-of-line)
  3107.   (if dired-trivial-filenames (dired-goto-next-nontrivial-file)))
  3108.  
  3109. ;;; moving by subdirectories
  3110.  
  3111. (defun dired-subdir-index (dir)
  3112.   ;; Return an index into alist for use with nth
  3113.   ;; for the sake of subdir moving commands.
  3114.   (let (found (index 0) (alist dired-subdir-alist))
  3115.     (while alist
  3116.       (if (string= dir (car (car alist)))
  3117.       (setq alist nil found t)
  3118.     (setq alist (cdr alist) index (1+ index))))
  3119.     (if found index nil)))
  3120.  
  3121. (defun dired-next-subdir (arg &optional no-error-if-not-found no-skip)
  3122.   "Go to next subdirectory, regardless of level."
  3123.   ;; Use 0 arg to go to this directory's header line.
  3124.   ;; NO-SKIP prevents moving to end of header line, returning whatever
  3125.   ;; position was found in dired-subdir-alist.
  3126.   (interactive "_p")
  3127.   (let ((this-dir (dired-current-directory))
  3128.     pos index)
  3129.     ;; nth with negative arg does not return nil but the first element
  3130.     (setq index (- (dired-subdir-index this-dir) arg))
  3131.     (setq pos (if (>= index 0)
  3132.           (dired-get-subdir-min (nth index dired-subdir-alist))))
  3133.     (if pos
  3134.     (progn
  3135.       (goto-char pos)
  3136.       (or no-skip (skip-chars-forward "^\n\r"))
  3137.       (point))
  3138.       (if no-error-if-not-found
  3139.       nil                ; return nil if not found
  3140.     (error "%s directory" (if (> arg 0) "Last" "First"))))))
  3141.  
  3142. (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
  3143.   "Go to previous subdirectory, regardless of level.
  3144. When called interactively and not on a subdir line, go to this subdir's line."
  3145.   ;;(interactive "_p")
  3146.   (interactive
  3147.    (list (if current-prefix-arg
  3148.          (prefix-numeric-value current-prefix-arg)
  3149.        ;; if on subdir start already, don't stay there!
  3150.        (if (dired-get-subdir) 1 0))))
  3151.   (dired-next-subdir (- arg) no-error-if-not-found no-skip))
  3152.  
  3153. (defun dired-tree-up (arg)
  3154.   "Go up ARG levels in the dired tree."
  3155.   (interactive "_p")
  3156.   (let ((dir (dired-current-directory)))
  3157.     (while (>= arg 1)
  3158.       (setq arg (1- arg)
  3159.         dir (file-name-directory (directory-file-name dir))))
  3160.     ;;(setq dir (expand-file-name dir))
  3161.     (or (dired-goto-subdir dir)
  3162.     (error "Cannot go up to %s - not in this tree." dir))))
  3163.  
  3164. (defun dired-tree-down ()
  3165.   "Go down in the dired tree."
  3166.   (interactive "_")
  3167.   (let ((dir (dired-current-directory)) ; has slash
  3168.     pos case-fold-search)        ; filenames are case sensitive
  3169.     (let ((rest (reverse dired-subdir-alist)) elt)
  3170.       (while rest
  3171.     (setq elt (car rest)
  3172.           rest (cdr rest))
  3173.     (if (dired-in-this-tree (directory-file-name (car elt)) dir)
  3174.         (setq rest nil
  3175.           pos (dired-goto-subdir (car elt))))))
  3176.     (if pos
  3177.     (goto-char pos)
  3178.       (error "At the bottom"))))
  3179.  
  3180. ;;; hiding
  3181.  
  3182. (defun dired-subdir-hidden-p (dir)
  3183.   (and selective-display
  3184.        (save-excursion
  3185.      (dired-goto-subdir dir)
  3186.      (looking-at "\r"))))
  3187.  
  3188. (defun dired-unhide-subdir ()
  3189.   (let (buffer-read-only)
  3190.     (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
  3191.  
  3192. (defun dired-hide-check ()
  3193.   (or selective-display
  3194.       (error "selective-display must be t for subdir hiding to work!")))
  3195.  
  3196. (defun dired-hide-subdir (arg)
  3197.   "Hide or unhide the current subdirectory and move to next directory.
  3198. Optional prefix arg is a repeat factor.
  3199. Use \\[dired-hide-all] to (un)hide all directories."
  3200.   (interactive "p")
  3201.   (dired-hide-check)
  3202.   (while (>=  (setq arg (1- arg)) 0)
  3203.     (let* ((cur-dir (dired-current-directory))
  3204.        (hidden-p (dired-subdir-hidden-p cur-dir))
  3205.        (elt (assoc cur-dir dired-subdir-alist))
  3206.        (end-pos (1- (dired-get-subdir-max elt)))
  3207.        buffer-read-only)
  3208.       ;; keep header line visible, hide rest
  3209.       (goto-char (dired-get-subdir-min elt))
  3210.       (skip-chars-forward "^\n\r")
  3211.       (if hidden-p
  3212.       (subst-char-in-region (point) end-pos ?\r ?\n)
  3213.     (subst-char-in-region (point) end-pos ?\n ?\r)))
  3214.     (dired-next-subdir 1 t)))
  3215.  
  3216. (defun dired-hide-all (arg)
  3217.   "Hide all subdirectories, leaving only their header lines.
  3218. If there is already something hidden, make everything visible again.
  3219. Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
  3220.   (interactive "P")
  3221.   (dired-hide-check)
  3222.   (let (buffer-read-only)
  3223.     (if (save-excursion
  3224.       (goto-char (point-min))
  3225.       (search-forward "\r" nil t))
  3226.     ;; unhide - bombs on \r in filenames
  3227.     (subst-char-in-region (point-min) (point-max) ?\r ?\n)
  3228.       ;; hide
  3229.       (let ((pos (point-max))        ; pos of end of last directory
  3230.         (alist dired-subdir-alist))
  3231.     (while alist            ; while there are dirs before pos
  3232.       (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
  3233.                 (save-excursion
  3234.                   (goto-char pos) ; current dir
  3235.                   ;; we're somewhere on current dir's line
  3236.                   (forward-line -1)
  3237.                   (point))
  3238.                 ?\n ?\r)
  3239.       (setq pos (dired-get-subdir-min (car alist)))    ; prev dir gets current dir
  3240.       (setq alist (cdr alist)))))))
  3241.  
  3242.  
  3243. ;; This function is the heart of tree dired.
  3244. ;; It is called for each retrieved filename.
  3245. ;; It could stand to be faster, though it's mostly function call
  3246. ;; overhead.  Avoiding to funcall seems to save about 10% in
  3247. ;; dired-get-filename.  Make it a defsubst?
  3248. (defun dired-current-directory (&optional localp)
  3249.   "Return the name of the subdirectory to which this line belongs.
  3250. This returns a string with trailing slash, like `default-directory'.
  3251. Optional argument means return a file name relative to `default-directory'."
  3252.   (let ((here (point))
  3253.     (alist (or dired-subdir-alist
  3254.            ;; probably because called in a non-dired buffer
  3255.            (error "No subdir-alist in %s" (current-buffer))))
  3256.     elt dir)
  3257.     (while alist
  3258.       (setq elt (car alist)
  3259.         dir (car elt)
  3260.         ;; use `<=' (not `<') as subdir line is part of subdir
  3261.         alist (if (<= (dired-get-subdir-min elt) here)
  3262.               nil        ; found
  3263.             (cdr alist))))
  3264.     (if localp
  3265.     (dired-make-relative dir default-directory)
  3266.       dir)))
  3267.  
  3268. ;; Subdirs start at the beginning of their header lines and end just
  3269. ;; before the beginning of the next header line (or end of buffer).
  3270.  
  3271. (defun dired-subdir-min ()
  3272.   (save-excursion
  3273.     (if (not (dired-prev-subdir 0 t t))
  3274.     (error "Not in a subdir!")
  3275.       (point))))
  3276.  
  3277. (defun dired-subdir-max ()
  3278.   (save-excursion
  3279.     (if (not (dired-next-subdir 1 t t))
  3280.     (point-max)
  3281.       (point))))
  3282.  
  3283. (defun dired-kill-line-or-subdir (&optional arg)
  3284.   "Kill this line (but not this file).
  3285. Optional prefix argument is a repeat factor.
  3286. If file is displayed as in situ subdir, kill that as well.
  3287. If on a subdir headerline, kill whole subdir."
  3288.   (interactive "p")
  3289.   (if (dired-get-subdir)
  3290.       (dired-kill-subdir)
  3291.     (dired-kill-line arg)))
  3292.  
  3293. (defun dired-kill-line (&optional arg)
  3294.   (interactive "P")
  3295.   (setq arg (prefix-numeric-value arg))
  3296.   (let (buffer-read-only file)
  3297.     (while (/= 0 arg)
  3298.       (setq file (dired-get-filename nil t))
  3299.       (if (not file)
  3300.       (error "Can only kill file lines.")
  3301.     (save-excursion (and file
  3302.                  (dired-goto-subdir file)
  3303.                  (dired-kill-subdir)))
  3304.     (delete-region (progn (beginning-of-line) (point))
  3305.                (progn (forward-line 1) (point)))
  3306.     (if (> arg 0)
  3307.         (setq arg (1- arg))
  3308.       (setq arg (1+ arg))
  3309.       (forward-line -1))))
  3310.     (dired-move-to-filename)))
  3311.  
  3312. (defun dired-kill-subdir (&optional remember-marks)
  3313.   "Remove all lines of current subdirectory.
  3314. Lower levels are unaffected."
  3315.   ;; With optional REMEMBER-MARKS, return a mark-alist.
  3316.   (interactive)
  3317.   (let ((beg (dired-subdir-min))
  3318.     (end (dired-subdir-max))
  3319.     buffer-read-only cur-dir)
  3320.     (setq cur-dir (dired-current-directory))
  3321.     (if (equal cur-dir default-directory)
  3322.     (error "Attempt to kill top level directory"))
  3323.     (prog1
  3324.     (if remember-marks (dired-remember-marks beg end))
  3325.       (delete-region beg end)
  3326.       (if (eobp)            ; don't leave final blank line
  3327.       (delete-char -1))
  3328.       (dired-unsubdir cur-dir))))
  3329.  
  3330. (defun dired-do-kill (&optional arg fmt)
  3331.   "Kill all marked lines (not files).
  3332. With a prefix arg, kill all lines not marked or flagged."
  3333.   ;; Returns count of killed lines.  FMT="" suppresses message.
  3334.   (interactive "P")
  3335.   (save-excursion
  3336.     (goto-char (point-min))
  3337.     (let (buffer-read-only (count 0))
  3338.       (if (not arg)            ; kill marked lines
  3339.       (let ((regexp (dired-marker-regexp)))
  3340.         (while (and (not (eobp))
  3341.             (re-search-forward regexp nil t))
  3342.           (setq count (1+ count))
  3343.           (delete-region (progn (beginning-of-line) (point))
  3344.                  (progn (forward-line 1) (point)))))
  3345.     ;; else kill unmarked lines
  3346.     (while (not (eobp))
  3347.       (if (or (dired-between-files)
  3348.           (not (looking-at "^  ")))
  3349.           (forward-line 1)
  3350.         (setq count (1+ count))
  3351.         (delete-region (point) (save-excursion
  3352.                      (forward-line 1)
  3353.                      (point))))))
  3354.       (or (equal "" fmt)
  3355.       (message (or fmt "Killed %d line%s.") count (dired-plural-s count)))
  3356.       count)))
  3357.  
  3358. (defun dired-do-redisplay (&optional arg test-for-subdir)
  3359.   "Redisplay all marked (or next ARG) files.
  3360.  
  3361. If on a subdir line, redisplay that subdirectory.  In that case,
  3362. a prefix arg lets you edit the ls switches used for the new listing."
  3363.   ;; Moves point if the next ARG files are redisplayed.
  3364.   (interactive "P\np")
  3365.   (if (and test-for-subdir (dired-get-subdir))
  3366.       (dired-insert-subdir
  3367.        (dired-get-subdir)
  3368.        (if arg (read-string "Switches for listing: " dired-actual-switches)))
  3369.     (message "Redisplaying...")
  3370.     ;; message instead of making dired-mark-map show-progress is much faster
  3371.     (dired-mark-map (let ((fname (dired-get-filename)))
  3372.               (message "Redisplaying... %s" fname)
  3373.               (dired-update-file-line fname))
  3374.             arg)
  3375.     (dired-move-to-filename)
  3376.     (message "Redisplaying...done")))
  3377.  
  3378. (defun dired-mark-files-in-region (start end)
  3379.   (let (buffer-read-only)
  3380.     (if (> start end)
  3381.     (error "start > end"))
  3382.     (goto-char start)            ; assumed at beginning of line
  3383.     (while (< (point) end)
  3384.       ;; Skip subdir line and following garbage like the `total' line:
  3385.       (while (and (< (point) end) (dired-between-files))
  3386.     (forward-line 1))
  3387.       (if (and (not (looking-at dired-re-dot))
  3388.            (dired-get-filename nil t))
  3389.       (progn
  3390.         (delete-char 1)
  3391.         (insert dired-marker-char)))
  3392.       (forward-line 1))))
  3393.  
  3394. (defun dired-mark-subdir-files ()
  3395.   "Mark all files except `.' and `..'."
  3396.   (interactive "P")
  3397.   (let ((p-min (dired-subdir-min)))
  3398.     (dired-mark-files-in-region p-min (dired-subdir-max))))
  3399.  
  3400. (defun dired-mark-subdir-or-file (arg)
  3401.   "Mark the current (or next ARG) files.
  3402. If on a subdir headerline, mark all its files except `.' and `..'.
  3403.  
  3404. Use \\[dired-unflag-all-files] to remove all marks
  3405. and \\[dired-unmark-subdir-or-file] on a subdir to remove the marks in
  3406. this subdir."
  3407.   (interactive "P")
  3408.   (if (dired-get-subdir)
  3409.       (save-excursion (dired-mark-subdir-files))
  3410.     (dired-mark-file (prefix-numeric-value arg))))
  3411.  
  3412. (defun dired-unmark-subdir-or-file (arg)
  3413.   "Unmark the current (or next ARG) files.
  3414. If looking at a subdir, unmark all its files except `.' and `..'."
  3415.   (interactive "P")
  3416.   (let ((dired-marker-char ?\040))
  3417.     (dired-mark-subdir-or-file arg)))
  3418.  
  3419. ;;; 5K
  3420. ;;;###begin dired-ins.el
  3421.  
  3422. (defun dired-maybe-insert-subdir (dirname &optional
  3423.                       switches no-error-if-not-dir-p)
  3424.   "Insert this subdirectory into the same dired buffer.
  3425. If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
  3426.   else inserts it at its natural place (as ls -lR would have done).
  3427. With a prefix arg, you may edit the ls switches used for this listing.
  3428.   You can add `R' to the switches to expand the whole tree starting at
  3429.   this subdirectory.
  3430. This function takes some pains to conform to ls -lR output."
  3431.   (interactive
  3432.    (list (dired-get-filename)
  3433.      (if current-prefix-arg
  3434.          (read-string "Switches for listing: " dired-actual-switches))))
  3435.   (let ((opoint (point)))
  3436.     ;; We don't need a marker for opoint as the subdir is always
  3437.     ;; inserted *after* opoint.
  3438.     (setq dirname (file-name-as-directory dirname))
  3439.     (or (and (not switches)
  3440.          (dired-goto-subdir dirname))
  3441.     (dired-insert-subdir dirname switches no-error-if-not-dir-p))
  3442.     ;; Push mark so that it's easy to find back.  Do this after the
  3443.     ;; insert message so that the user sees the `Mark set' message.
  3444.     (push-mark opoint)))
  3445.  
  3446. (defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
  3447.   "Insert this subdirectory into the same dired buffer.
  3448. If it is already present, overwrites previous entry,
  3449.   else inserts it at its natural place (as ls -lR would have done).
  3450. With a prefix arg, you may edit the ls switches used for this listing.
  3451.   You can add `R' to the switches to expand the whole tree starting at
  3452.   this subdirectory.
  3453. This function takes some pains to conform to ls -lR output."
  3454.   ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
  3455.   ;; Prospero where dired-ls does the right thing, but
  3456.   ;; file-directory-p has not been redefined.
  3457.   (interactive
  3458.    (list (dired-get-filename)
  3459.      (if current-prefix-arg
  3460.          (read-string "Switches for listing: " dired-actual-switches))))
  3461.   (setq dirname (file-name-as-directory (expand-file-name dirname)))
  3462.   (dired-insert-subdir-validate dirname switches)
  3463.   (or no-error-if-not-dir-p
  3464.       (file-directory-p dirname)
  3465.       (error  "Attempt to insert a non-directory: %s" dirname))
  3466.   (let ((elt (assoc dirname dired-subdir-alist))
  3467.      switches-have-R mark-alist case-fold-search buffer-read-only)
  3468.     ;; case-fold-search is nil now, so we can test for capital `R':
  3469.     (if (setq switches-have-R (and switches (string-match "R" switches)))
  3470.     ;; avoid duplicated subdirs
  3471.     (setq mark-alist (dired-kill-tree dirname t)))
  3472.     (if elt
  3473.     ;; If subdir is already present, remove it and remember its marks
  3474.     (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
  3475.       (dired-insert-subdir-newpos dirname)) ; else compute new position
  3476.     (dired-insert-subdir-doupdate
  3477.      dirname elt (dired-insert-subdir-doinsert dirname switches))
  3478.     (if switches-have-R (dired-build-subdir-alist))
  3479.     (dired-initial-position dirname)
  3480.     (save-excursion (dired-mark-remembered mark-alist))))
  3481.  
  3482. ;; This is a separate function for dired-vms.
  3483. (defun dired-insert-subdir-validate (dirname &optional switches)
  3484.   ;; Check that it is valid to insert DIRNAME with SWITCHES.
  3485.   ;; Signal an error if invalid (e.g. user typed `i' on `..').
  3486.   (or (dired-in-this-tree dirname default-directory)
  3487.       (error  "%s: not in this directory tree" dirname))
  3488.   (if switches
  3489.       (let (case-fold-search)
  3490.     (mapcar
  3491.      (function
  3492.       (lambda (x)
  3493.         (or (eq (null (string-match x switches))
  3494.             (null (string-match x dired-actual-switches)))
  3495.         (error "Can't have dirs with and without -%s switches together"
  3496.                x))))
  3497.      ;; all switches that make a difference to dired-get-filename:
  3498.      '("F" "b")))))
  3499.  
  3500. (defun dired-kill-tree (dirname &optional remember-marks)
  3501.   ;;"Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
  3502.   ;; With optional arg REMEMBER-MARKS, return an alist of marked files."
  3503.   (interactive "DKill tree below directory: ")
  3504.   (let ((s-alist dired-subdir-alist) dir m-alist)
  3505.     (while s-alist
  3506.       (setq dir (car (car s-alist))
  3507.         s-alist (cdr s-alist))
  3508.       (if (and (not (string-equal dir dirname))
  3509.            (dired-in-this-tree dir dirname)
  3510.            (dired-goto-subdir dir))
  3511.       (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
  3512.     m-alist))
  3513.  
  3514. (defun dired-insert-subdir-newpos (new-dir)
  3515.   ;; Find pos for new subdir, according to tree order.
  3516.   (let ((alist dired-subdir-alist) elt dir pos new-pos)
  3517.     (while alist
  3518.       (setq elt (car alist)
  3519.         alist (cdr alist)
  3520.         dir (car elt)
  3521.         pos (dired-get-subdir-min elt))
  3522.       (if (dired-tree-lessp dir new-dir)
  3523.       ;; Insert NEW-DIR after DIR
  3524.       (setq new-pos (dired-get-subdir-max elt)
  3525.         alist nil)))
  3526.     (goto-char new-pos))
  3527.   ;; want a separating newline between subdirs
  3528.   (or (eobp)
  3529.       (forward-line -1))
  3530.   (insert "\n")
  3531.   (point))
  3532.  
  3533. (defun dired-insert-subdir-del (element)
  3534.   ;; Erase an already present subdir (given by ELEMENT) from buffer.
  3535.   ;; Move to that buffer position.  Return a mark-alist.
  3536.   (let ((begin-marker (dired-get-subdir-min element)))
  3537.     (goto-char begin-marker)
  3538.     ;; Are at beginning of subdir (and inside it!).  Now determine its end:
  3539.     (goto-char (dired-subdir-max))
  3540.     (or (eobp);; want a separating newline _between_ subdirs:
  3541.     (forward-char -1))
  3542.     (prog1
  3543.     (dired-remember-marks begin-marker (point))
  3544.       (delete-region begin-marker (point)))))
  3545.  
  3546. (defun dired-insert-subdir-doinsert (dirname switches)
  3547.   ;; Insert ls output after point and put point on the correct
  3548.   ;; position for the subdir alist.
  3549.   ;; Return the boundary of the inserted text (as list of BEG and END).
  3550.   (let ((begin (point)) end)
  3551.     (message "Reading directory %s..." dirname)
  3552.     (let ((dired-actual-switches
  3553.        (or switches
  3554.            (dired-replace-in-string "R" "" dired-actual-switches))))
  3555.       (if (equal dirname (car (car (reverse dired-subdir-alist))))
  3556.       ;; top level directory may contain wildcards:
  3557.       (dired-readin-insert dired-directory)
  3558.     (dired-ls dirname dired-actual-switches nil t)))
  3559.     (message "Reading directory %s...done" dirname)
  3560.     (setq end (point-marker))
  3561.     (dired-indent-rigidly begin end 2)
  3562.     ;;  call dired-insert-headerline afterwards, as under VMS dired-ls
  3563.     ;;  does insert the headerline itself and the insert function just
  3564.     ;;  moves point.
  3565.     ;;  Need a marker for END as this inserts text.
  3566.     (goto-char begin)
  3567.     (dired-insert-headerline dirname)
  3568.     ;; point is now like in dired-build-subdir-alist
  3569.     (prog1
  3570.     (list begin (marker-position end))
  3571.       (set-marker end nil))))
  3572.  
  3573. (defun dired-insert-subdir-doupdate (dirname elt beg-end)
  3574.   ;; Point is at the correct subdir alist position for ELT,
  3575.   ;; BEG-END is the subdir-region (as list of begin and end).
  3576.   (if elt                ; subdir was already present
  3577.       ;; update its position (should actually be unchanged)
  3578.       (set-marker (dired-get-subdir-min elt) (point-marker))
  3579.     (dired-alist-add dirname (point-marker)))
  3580.   ;; The hook may depend on the subdir-alist containing the just
  3581.   ;; inserted subdir, so run it after dired-alist-add:
  3582.   (if dired-after-readin-hook
  3583.       (save-excursion
  3584.     (let ((begin (nth 0 beg-end))
  3585.           (end (nth 1 beg-end)))
  3586.       (goto-char begin)
  3587.       (save-restriction
  3588.         (narrow-to-region begin end)
  3589.         ;; hook may add or delete lines, but the subdir boundary
  3590.         ;; marker floats
  3591.         (run-hooks 'dired-after-readin-hook))))))
  3592.  
  3593. (defun dired-tree-lessp (dir1 dir2)
  3594.   ;; Lexicographic order on pathname components, like `ls -lR':
  3595.   ;; DIR1 < DIR2 iff DIR1 comes *before* DIR2 in an `ls -lR' listing,
  3596.   ;;   i.e., iff DIR1 is a (grand)parent dir of DIR2,
  3597.   ;;   or DIR1 and DIR2 are in the same parentdir and their last
  3598.   ;;   components are string-lessp.
  3599.   ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
  3600.   ;; string-lessp could arguably be replaced by file-newer-than-file-p
  3601.   ;;   if dired-actual-switches contained `t'.
  3602.   (setq dir1 (file-name-as-directory dir1)
  3603.     dir2 (file-name-as-directory dir2))
  3604.   (let ((components-1 (dired-split "/" dir1))
  3605.     (components-2 (dired-split "/" dir2)))
  3606.     (while (and components-1
  3607.         components-2
  3608.         (equal (car components-1) (car components-2)))
  3609.       (setq components-1 (cdr components-1)
  3610.         components-2 (cdr components-2)))
  3611.     (let ((c1 (car components-1))
  3612.       (c2 (car components-2)))
  3613.  
  3614.       (cond ((and c1 c2)
  3615.          (string-lessp c1 c2))
  3616.         ((and (null c1) (null c2))
  3617.          nil)            ; they are equal, not lessp
  3618.         ((null c1)            ; c2 is a subdir of c1: c1<c2
  3619.          t)
  3620.         ((null c2)            ; c1 is a subdir of c2: c1>c2
  3621.          nil)
  3622.         (t (error "This can't happen"))))))
  3623.  
  3624. ;; There should be a builtin split function - inverse to mapconcat.
  3625. (defun dired-split (pat str &optional limit)
  3626.   "Splitting on regexp PAT, turn string STR into a list of substrings.
  3627. Optional third arg LIMIT (>= 1) is a limit to the length of the
  3628. resulting list.
  3629. Thus, if SEP is a regexp that only matches itself,
  3630.  
  3631.    (mapconcat 'identity (dired-split SEP STRING) SEP)
  3632.  
  3633. is always equal to STRING."
  3634.   (let* ((start (string-match pat str))
  3635.      (result (list (substring str 0 start)))
  3636.      (count 1)
  3637.      (end (if start (match-end 0))))
  3638.     (if end                ; else nothing left
  3639.     (while (and (or (not (integerp limit))
  3640.             (< count limit))
  3641.             (string-match pat str end))
  3642.       (setq start (match-beginning 0)
  3643.         count (1+ count)
  3644.         result (cons (substring str end start) result)
  3645.         end (match-end 0)
  3646.         start end)
  3647.       ))
  3648.     (if (and (or (not (integerp limit))
  3649.          (< count limit))
  3650.          end)            ; else nothing left
  3651.     (setq result
  3652.           (cons (substring str end) result)))
  3653.     (nreverse result)))
  3654.  
  3655. (defun dired-indent-rigidly (start end arg)
  3656.   ;; like indent-rigidly but has more efficient behavior w.r.t. the
  3657.   ;; after-change-functions (i.e., font-lock-mode.)
  3658.   (save-excursion
  3659.     (let ((after-change-functions nil)
  3660.       (after-change-function nil))
  3661.       (goto-char end)
  3662.       (indent-rigidly start end arg))
  3663.     ;; deletion
  3664.     (run-hook-with-args 'after-change-functions start start (- end start))
  3665.     (run-hook-with-args 'after-change-function  start start (- end start))
  3666.     ;; insertion
  3667.     (run-hook-with-args 'after-change-functions start (point) 0)
  3668.     (run-hook-with-args 'after-change-function  start (point) 0)
  3669.     ))
  3670.  
  3671. (if (string-lessp emacs-version "19")
  3672.     (fset 'dired-indent-rigidly (symbol-function 'indent-rigidly)))
  3673.  
  3674. ;;;###end dired-ins.el
  3675.  
  3676.  
  3677. ;;; Sorting
  3678.  
  3679. ;; Most ls can only sort by name or by date (with -t), nothing else.
  3680. ;; GNU ls sorts on size with -S, on extension with -X, and unsorted with -U.
  3681. ;; So anything that does not contain these is sort "by name".
  3682.  
  3683. (defvar dired-ls-sorting-switches "SXU"
  3684.   "String of ls switches (single letters) except `t' that influence sorting.")
  3685.  
  3686. (defvar dired-sort-by-date-regexp
  3687.   (concat "^-[^" dired-ls-sorting-switches
  3688.       "]*t[^" dired-ls-sorting-switches "]*$")
  3689.   "Regexp recognized by dired to set `by date' mode.")
  3690.  
  3691. (defvar dired-sort-by-name-regexp
  3692.   (concat "^-[^t" dired-ls-sorting-switches "]+$")
  3693.   "Regexp recognized by dired to set `by name' mode.")
  3694.  
  3695. (defvar dired-sort-mode nil
  3696.   "Whether Dired sorts by name, date etc. (buffer-local).")
  3697. ;; This is nil outside dired buffers so it can be used in the modeline
  3698.  
  3699. (defun dired-sort-set-modeline ()
  3700.   ;; Set modeline display according to dired-actual-switches.
  3701.   ;; Modeline display of "by name" or "by date" guarantees the user a
  3702.   ;; match with the corresponding regexps.  Non-matching switches are
  3703.   ;; shown literally.
  3704.   (setq dired-sort-mode
  3705.     (let (case-fold-search)
  3706.       (cond ((string-match dired-sort-by-name-regexp dired-actual-switches)
  3707.          " by name")
  3708.         ((string-match dired-sort-by-date-regexp dired-actual-switches)
  3709.          " by date")
  3710.         (t
  3711.          (concat " " dired-actual-switches)))))
  3712.   ;; update mode line:
  3713.   (set-buffer-modified-p (buffer-modified-p)))
  3714.  
  3715. (defun dired-sort-toggle-or-edit (&optional arg)
  3716.   "Toggle between sort by date/name and refresh the dired buffer.
  3717. With a prefix argument you can edit the current listing switches instead."
  3718.   (interactive "P")
  3719.   (if arg
  3720.       (dired-sort-other
  3721.        (read-string "ls switches (must contain -l): " dired-actual-switches))
  3722.     (dired-sort-toggle)))
  3723.  
  3724. (defun dired-sort-toggle ()
  3725.   ;; Toggle between sort by date/name.  Reverts the buffer.
  3726.   (setq dired-actual-switches
  3727.     (let (case-fold-search)
  3728.       (concat
  3729.        "-l"
  3730.        (dired-replace-in-string (concat "[---lt"
  3731.                         dired-ls-sorting-switches "]")
  3732.                     ""
  3733.                     dired-actual-switches)
  3734.        (if (string-match (concat "[t" dired-ls-sorting-switches "]")
  3735.                  dired-actual-switches)
  3736.            ""
  3737.          "t"))))
  3738.   (dired-sort-set-modeline)
  3739.   (revert-buffer))
  3740.  
  3741. (defun dired-sort-other (switches &optional no-revert)
  3742.   ;; Specify new ls SWITCHES for current dired buffer.  Values matching
  3743.   ;; `dired-sort-by-date-regexp' or `dired-sort-by-name-regexp' set the
  3744.   ;; minor mode accordingly, others appear literally in the mode line.
  3745.   ;; With optional second arg NO-REVERT, don't refresh the listing afterwards.
  3746.   (setq dired-actual-switches switches)
  3747.   (dired-sort-set-modeline)
  3748.   (or no-revert (revert-buffer)))
  3749.  
  3750. (if (eq system-type 'vax-vms)
  3751.     (load "dired-vms"))
  3752.  
  3753. (if (string-match "XEmacs" emacs-version)
  3754.     (load "dired-xemacs-menu"))
  3755.  
  3756. (run-hooks 'dired-load-hook)        ; for your customizations
  3757.